code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package org.transdroid.gui.util;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
public abstract class SelectableArrayAdapter<T> extends ArrayAdapter<T> {
private List<T> selected;
private OnSelectedChangedListener listener;
public SelectableArrayAdapter(Context context, List<T> objects, OnSelectedChangedListener listener) {
this(context, objects);
this.listener = listener;
}
public SelectableArrayAdapter(Context context, List<T> objects) {
super(context, objects);
this.selected = new ArrayList<T>();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getView(position, convertView, parent, selected.contains(getItem(position)));
}
public abstract View getView(int position, View convertView, ViewGroup paret, boolean selected);
/**
* Is called by views to indicate an item was either selected or deselected
* @param item The item for which the selected state has changed
* @param isChecked If the item is now checked/selected
*/
public void itemChecked(T item, boolean isChecked) {
if (!isChecked && selected.contains(item)) {
selected.remove(item);
}
if (isChecked && !selected.contains(item)) {
selected.add(item);
}
if (listener != null) {
listener.onSelectedResultsChanged();
}
}
/**
* Whether an item is currently selected
* @param item The item, which should be present in the underlying list
* @return True if the item is currently selected, false otherwise
*/
public boolean isItemChecked(T item) {
return selected.contains(item);
}
@Override
public void replace(List<T> objects) {
// Reset the 'selected' list as well
this.selected.clear();
super.replace(objects);
if (listener != null) {
listener.onSelectedResultsChanged();
}
}
/**
* Returns the list of all checked/selected items
* @return The list of selected items
*/
public List<T> getSelected() {
return this.selected;
}
/**
* Clears the entire item selection, leaving it empty
*/
public void clearSelection() {
this.selected.clear();
if (listener != null) {
listener.onSelectedResultsChanged();
}
}
public void invertSelection() {
for (T item : getAllItems()) {
if (selected.contains(item)) {
selected.remove(item);
} else {
selected.add(item);
}
}
if (listener != null) {
listener.onSelectedResultsChanged();
}
}
/**
* Listener to changes in the state of selected items in an ArrayAdapter
*/
public interface OnSelectedChangedListener {
public void onSelectedResultsChanged();
}
}
| Java |
/*
* Copyright (C) 2006 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.
*
* This ArrayList class is copied from android.widget.ArrayList and
* adjusted in three ways: 1) loading from resources is no longer supported,
* 2) a public method is added to allow replacing of the while list, and
* 3) it is made abstract, requiring to override getView (no more setting
* of the resource id to show)
*/
package org.transdroid.gui.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
/**
* A ListAdapter that manages a ListView backed by an array of arbitrary
* objects. getView needs to be overridden to determine the view to show
* for an object in the list.
*/
public abstract class ArrayAdapter<T> extends BaseAdapter implements Filterable {
/**
* Contains the list of objects that represent the data of this ArrayAdapter.
* The content of this list is referred to as "the array" in the documentation.
*/
private List<T> mObjects;
/**
* Lock used to modify the content of {@link #mObjects}. Any write operation
* performed on the array should be synchronized on this lock. This lock is also
* used by the filter (see {@link #getFilter()} to make a synchronized copy of
* the original array of data.
*/
private final Object mLock = new Object();
/**
* Indicates whether or not {@link #notifyDataSetChanged()} must be called whenever
* {@link #mObjects} is modified.
*/
private boolean mNotifyOnChange = true;
private Context mContext;
private ArrayList<T> mOriginalValues;
private ArrayFilter mFilter;
/**
* Constructor
*
* @param context The current context.
*/
public ArrayAdapter(Context context) {
init(context, new ArrayList<T>());
}
/**
* Constructor
*
* @param context The current context.
* @param objects The objects to represent in the ListView.
*/
public ArrayAdapter(Context context, T[] objects) {
init(context, Arrays.asList(objects));
}
/**
* Constructor
*
* @param context The current context.
* @param objects The objects to represent in the ListView.
*/
public ArrayAdapter(Context context, List<T> objects) {
init(context, objects);
}
/**
* Adds the specified object at the end of the array.
*
* @param object The object to add at the end of the array.
*/
public void add(T object) {
if (mOriginalValues != null) {
synchronized (mLock) {
mOriginalValues.add(object);
if (mNotifyOnChange) notifyDataSetChanged();
}
} else {
mObjects.add(object);
if (mNotifyOnChange) notifyDataSetChanged();
}
}
/**
* Inserts the specified object at the specified index in the array.
*
* @param object The object to insert into the array.
* @param index The index at which the object must be inserted.
*/
public void insert(T object, int index) {
if (mOriginalValues != null) {
synchronized (mLock) {
mOriginalValues.add(index, object);
if (mNotifyOnChange) notifyDataSetChanged();
}
} else {
mObjects.add(index, object);
if (mNotifyOnChange) notifyDataSetChanged();
}
}
/**
* Removes the specified object from the array.
*
* @param object The object to remove.
*/
public void remove(T object) {
if (mOriginalValues != null) {
synchronized (mLock) {
mOriginalValues.remove(object);
}
} else {
mObjects.remove(object);
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Remove all elements from the list.
*/
public void clear() {
if (mOriginalValues != null) {
synchronized (mLock) {
mOriginalValues.clear();
}
} else {
mObjects.clear();
}
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Sorts the content of this adapter using the specified comparator.
*
* @param comparator The comparator used to sort the objects contained
* in this adapter.
*/
public void sort(Comparator<? super T> comparator) {
Collections.sort(mObjects, comparator);
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* Replaces the underlying list some other list and notifies a listening view.
*
* @param objects The new list of data objects,
*/
public void replace(List<T> objects) {
init(getContext(), objects);
if (mNotifyOnChange) notifyDataSetChanged();
}
/**
* {@inheritDoc}
*/
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
mNotifyOnChange = true;
}
/**
* Control whether methods that change the list ({@link #add},
* {@link #insert}, {@link #remove}, {@link #clear}) automatically call
* {@link #notifyDataSetChanged}. If set to false, caller must
* manually call notifyDataSetChanged() to have the changes
* reflected in the attached view.
*
* The default is true, and calling notifyDataSetChanged()
* resets the flag to true.
*
* @param notifyOnChange if true, modifications to the list will
* automatically call {@link
* #notifyDataSetChanged}
*/
public void setNotifyOnChange(boolean notifyOnChange) {
mNotifyOnChange = notifyOnChange;
}
private void init(Context context, List<T> objects) {
mContext = context;
mObjects = objects;
}
/**
* Returns the context associated with this array adapter. The context is used
* to create views from the resource passed to the constructor.
*
* @return The Context associated with this adapter.
*/
public Context getContext() {
return mContext;
}
/**
* {@inheritDoc}
*/
public int getCount() {
return mObjects.size();
}
/**
* {@inheritDoc}
*/
public T getItem(int position) {
return mObjects.get(position);
}
/**
* Returns all objects in this adapter.
*
* @return The contained list of objects.
*/
public List<T> getAllItems() {
return mObjects;
}
/**
* Returns the position of the specified item in the array.
*
* @param item The item to retrieve the position of.
*
* @return The position of the specified item.
*/
public int getPosition(T item) {
return mObjects.indexOf(item);
}
/**
* {@inheritDoc}
*/
public long getItemId(int position) {
return position;
}
/**
* {@inheritDoc}
*/
public abstract View getView(int position, View convertView, ViewGroup parent);
/**
* {@inheritDoc}
*/
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
/**
* <p>An array filter constrains the content of the array adapter with
* a prefix. Each item that does not start with the supplied prefix
* is removed from the list.</p>
*/
private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<T>(mObjects);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (mLock) {
ArrayList<T> list = new ArrayList<T>(mOriginalValues);
results.values = list;
results.count = list.size();
}
} else {
String prefixString = prefix.toString().toLowerCase();
final ArrayList<T> values = mOriginalValues;
final int count = values.size();
final ArrayList<T> newValues = new ArrayList<T>(count);
for (int i = 0; i < count; i++) {
final T value = values.get(i);
final String valueText = value.toString().toLowerCase();
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
newValues.add(value);
} else {
final String[] words = valueText.split(" ");
final int wordCount = words.length;
for (int k = 0; k < wordCount; k++) {
if (words[k].startsWith(prefixString)) {
newValues.add(value);
break;
}
}
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mObjects = (List<T>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import java.net.MalformedURLException;
import java.net.URL;
import org.transdroid.R;
import org.transdroid.gui.util.ActivityUtil;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
/**
* Provides an activity in which the user can input a URL using a text box.
* Alternatively a file selector can be started for a local .torrent file. The
* URL or file location will then be forwarded to the Transdroid application.
*
* @author erickok
*
*/
public class Add extends Activity {
//private static final String LOG_NAME = "Add";
private final static String PICK_FILE_INTENT = "org.openintents.action.PICK_FILE";
private final static Uri OIFM_MARKET_URI = Uri.parse("market://search?q=pname:org.openintents.filemanager");
public static final int FILE_REQUEST_CODE = 1;
private static final int DIALOG_INSTALLFILEMANAGER = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_add);
// Add button click handlers
findViewById(R.id.ok).setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
parseInput();
}
});
findViewById(R.id.cancel).setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
setResult(RESULT_CANCELED);
finish();
}
});
findViewById(R.id.selectfile).setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StartSelectorIntent();
}
});
}
/**
* Parse the text input and return the given URL
*/
private void parseInput() {
// Get the URL text
EditText url = (EditText) findViewById(R.id.url);
String urlText = url.getText().toString();
// Check if no URL given
if (urlText == null || urlText.length() <= 0) {
Toast.makeText(this, R.string.no_valid_url, Toast.LENGTH_SHORT).show();
return;
}
// Magnet scheme is not supported by java.net.URL so instead we consider this to be okay manually
if (urlText != null && !urlText.startsWith("magnet")) {
// Check URL structure
try {
new URL(urlText); // Nothing is actually done with it; only for parsing
} catch (MalformedURLException e) {
Toast.makeText(this, R.string.no_valid_url, Toast.LENGTH_SHORT).show();
return;
}
}
// Create a result for the calling activity
Intent i = new Intent(this, Torrents.class);
i.setData(Uri.parse(urlText));
startActivity(i);
setResult(RESULT_OK);
finish();
}
/**
* Starts an Intent to pick a local .torrent file (usually form the SD card)
*/
private void StartSelectorIntent() {
// Test to see if a file manager is available that can handle the PICK_FILE intent, such as IO File Manager
Intent pick = new Intent(PICK_FILE_INTENT);
if (ActivityUtil.isIntentAvailable(this, pick)) {
// Ask the file manager to allow the user to pick a file
startActivityForResult(pick, FILE_REQUEST_CODE);
} else {
// Show a message if the user should install OI File Manager for this feature
showDialog(DIALOG_INSTALLFILEMANAGER);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_INSTALLFILEMANAGER:
return ActivityUtil.buildInstallDialog(this, R.string.oifm_not_found, OIFM_MARKET_URI);
}
return null;
}
/**
* A result was returned from the on of the intents
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_REQUEST_CODE:
// Did we receive a file name?
if (data != null && data.getData() != null && data.getData().toString() != "") {
// Create a result for the calling activity
Intent i = new Intent(this, Torrents.class);
i.setData(data.getData());
startActivity(i);
setResult(RESULT_OK);
finish();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import org.transdroid.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
/**
* Activity that loads the torrents fragment and, on tablet interfaces, hosts
* the details fragment.
*
* @author erickok
*/
public class Torrents extends SherlockFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_torrents);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
if (savedInstanceState == null) {
// Start the fragment for this torrent
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
TorrentsFragment fragment = new TorrentsFragment();
ft.replace(R.id.torrents, fragment);
ft.commit();
}
}
@Override
protected void onNewIntent(Intent i) {
loadData(i);
}
private void loadData(Intent i) {
((TorrentsFragment)getSupportFragmentManager().findFragmentById(R.id.torrents)).handleIntent(i);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.transdroid.R;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonMethod;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.IDaemonCallback;
import org.transdroid.daemon.Label;
import org.transdroid.daemon.TaskQueue;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.TorrentsComparator;
import org.transdroid.daemon.TorrentsSortBy;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
import org.transdroid.daemon.task.GetStatsTask;
import org.transdroid.daemon.task.GetStatsTaskSuccessResult;
import org.transdroid.daemon.task.PauseAllTask;
import org.transdroid.daemon.task.PauseTask;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.ResumeAllTask;
import org.transdroid.daemon.task.ResumeTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetAlternativeModeTask;
import org.transdroid.daemon.task.SetDownloadLocationTask;
import org.transdroid.daemon.task.SetLabelTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.task.StartAllTask;
import org.transdroid.daemon.task.StartTask;
import org.transdroid.daemon.task.StopAllTask;
import org.transdroid.daemon.task.StopTask;
import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.FileSizeConverter;
import org.transdroid.daemon.util.HttpHelper;
import org.transdroid.gui.SetLabelDialog.ResultListener;
import org.transdroid.gui.TorrentViewSelectorWindow.LabelSelectionListener;
import org.transdroid.gui.TorrentViewSelectorWindow.MainViewTypeSelectionListener;
import org.transdroid.gui.rss.RssFeeds;
import org.transdroid.gui.search.Search;
import org.transdroid.gui.util.ActivityUtil;
import org.transdroid.gui.util.DialogWrapper;
import org.transdroid.gui.util.ErrorLogSender;
import org.transdroid.gui.util.InterfaceSettings;
import org.transdroid.preferences.Preferences;
import org.transdroid.preferences.PreferencesMain;
import org.transdroid.search.barcode.GoogleWebSearchBarcodeResolver;
import org.transdroid.service.AlarmSettings;
import org.transdroid.service.BootReceiver;
import org.transdroid.util.TLog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SpinnerAdapter;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
/**
* The main screen for the Transdroid application and provides most on-the-surface functionality
* as well. Server daemon and search engine communication is wrapped in adapters.
*
* @author erickok
*
*/
public class TorrentsFragment extends SherlockFragment implements IDaemonCallback, OnTouchListener {
private static final String LOG_NAME = "Main";
private static final int ACTIVITY_PREFERENCES = 0;
private static final int ACTIVITY_DETAILS = 1;
private static final int ACTIVITY_BARCODE = 0x0000c0de;
private static final int DIALOG_SERVERS = 0;
private static final int DIALOG_RATES = 1;
private static final int DIALOG_CHANGELOG = 2;
private static final int DIALOG_ASKREMOVE = 3;
private static final int DIALOG_SETLABEL = 4;
private static final int DIALOG_ADDFAILED = 5;
private static final int DIALOG_SETDOWNLOADLOCATION = 6;
private static final int DIALOG_REFRESH_INTERVAL = 7;
private static final int DIALOG_INSTALLBARCODESCANNER = 8;
private static final int DIALOG_FILTER = 9;
private static final int MENU_ADD_ID = 1;
private static final int MENU_BARCODE_ID = 2;
private static final int MENU_RSS_ID = 3;
private static final int MENU_FORALL_ID = 4;
private static final int MENU_SORT_ID = 5;
private static final int MENU_SETTINGS_ID = 6;
private static final int MENU_CHANGELOG_ID = 7;
private static final int MENU_SWITCH_ID = 8;
private static final int MENU_RATES_ID = 9;
private static final int MENU_ERRORREPORT_ID = 10;
private static final int MENU_REFRESH_ID = 11;
private static final int MENU_SEARCH_ID = 12;
private static final int MENU_ALTMODE_ID = 13;
private static final int MENU_FORALL_GROUP_ID = 20;
private static final int MENU_FORALL_PAUSE_ID = 21;
private static final int MENU_FORALL_RESUME_ID = 22;
private static final int MENU_FORALL_STOP_ID = 23;
private static final int MENU_FORALL_START_ID = 24;
private static final int MENU_SORT_GROUP_ID = 30;
private static final int MENU_SORT_ALPHA_ID = 31;
private static final int MENU_SORT_STATUS_ID = 32;
private static final int MENU_SORT_DONE_ID = 33;
private static final int MENU_SORT_ADDED_ID = 34;
private static final int MENU_SORT_UPSPEED_ID = 35;
private static final int MENU_SORT_RATIO_ID = 36;
private static final int MENU_SORT_GTZERO_ID = 37;
private static final int MENU_PAUSE_ID = 41;
private static final int MENU_RESUME_ID = 42;
private static final int MENU_STOP_ID = 43;
private static final int MENU_START_ID = 44;
private static final int MENU_FORCESTART_ID = 45;
private static final int MENU_REMOVE_ID = 46;
private static final int MENU_REMOVE_DATA_ID = 47;
private static final int MENU_SETLABEL_ID = 48;
private static final int MENU_SETDOWNLOADLOCATION_ID = 49;
private static final int MENU_FILTER_ID = 60;
protected boolean useTabletInterface;
private Handler handler;
private Runnable refreshRunable;
private GestureDetector gestureDetector;
private TextView emptyText;
private TableLayout statusBox;
private TextView taskmessage, statusDown, statusUp, statusDownRate, statusUpRate;
private LinearLayout startsettings;
private ImageView viewtypeselector;
private TextView viewtype;
private LinearLayout controlbar;
private TorrentViewSelectorWindow viewtypeselectorpopup;
// Variables determining which view over the torrents to show
private TorrentsSortBy sortSetting = TorrentsSortBy.Alphanumeric;
private boolean sortReversed = false;
private MainViewType activeMainView = MainViewType.ShowAll;
private boolean onlyShowTransferring = false;
private List<String> availableLabels;
private String activeLabel = null;
private boolean inAlternativeMode = false; // Whether the server is in alternative (speed) mode (i.e. Transmission's Turtle Mode)
protected boolean ignoreFirstListNavigation = true;
private String activeFilter = null;
private List<Torrent> allTorrents;
private List<Label> allLabels;
private TaskQueue queue;
private boolean inProgress = false;
// Settings-related variables
private IDaemonAdapter daemon;
private static List<DaemonSettings> allDaemonSettings;
private static int lastUsedDaemonSettings;
private static InterfaceSettings interfaceSettings;
private static AlarmSettings alarmServiceSettings;
// Variables to store data to use inside the dialogs that we pop up
private Torrent selectedTorrent;
private boolean selectedRemoveData;
private String failedTorrentUri;
private String failedTorrentTitle;
public TorrentsFragment() {
setHasOptionsMenu(true);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
ignoreFirstListNavigation = true;
return inflater.inflate(R.layout.fragment_torrents, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Attach the Android TLog to the daemon logger
DLog.setLogger(TLog.getInstance());
// Set activity screen features
useTabletInterface = Transdroid.isTablet(getResources());
registerForContextMenu(getListView());
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(onTorrentClicked);
// Access UI widgets and title
emptyText = (TextView) findViewById(android.R.id.empty);
startsettings = (LinearLayout) findViewById(R.id.startsettings);
taskmessage = (TextView) findViewById(R.id.taskmessage);
statusBox = (TableLayout) findViewById(R.id.st_box);
statusDown = (TextView) findViewById(R.id.st_down);
statusDownRate = (TextView) findViewById(R.id.st_downrate);
statusUp = (TextView) findViewById(R.id.st_up);
statusUpRate = (TextView) findViewById(R.id.st_uprate);
setProgressBar(false);
// Open settings button
Button startsettingsButton = (Button) findViewById(R.id.startsettings_button);
startsettingsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Open settings screen
startActivityForResult(new Intent(getActivity(), PreferencesMain.class), ACTIVITY_PREFERENCES);
}
});
// Show a dialog allowing control over max. upload and download speeds
statusBox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DIALOG_RATES);
}
});
// The control bar and view type selector (quickaction popup)
controlbar = (LinearLayout) findViewById(R.id.controlbar);
viewtype = (TextView) findViewById(R.id.viewtype);
viewtypeselector = (ImageView) findViewById(R.id.viewtypeselector);
viewtypeselectorpopup = new TorrentViewSelectorWindow(viewtypeselector, new MainViewTypeSelectionListener() {
@Override
public void onMainViewTypeSelected(MainViewType newType) {
if (activeMainView != newType) {
// Show torrents for the new main view selection
activeMainView = newType;
updateTorrentsView(true);
}
}
}, new LabelSelectionListener() {
@Override
public void onLabelSelected(int labelPosition) {
String newLabel = availableLabels.get(labelPosition);
if (activeLabel != newLabel) {
// Show torrents for the new label selection
activeLabel = newLabel;
updateTorrentsView(true);
}
}
});
viewtypeselector.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
viewtypeselectorpopup.showLikePopDownMenu();
}
});
// Swiping (flinging) between server configurations (or labels)
gestureDetector = new GestureDetector(new MainScreenGestureListener());
getListView().setOnTouchListener(this);
emptyText.setOnTouchListener(this);
// Attach auto refresh handler
handler = new Handler();
refreshRunable = new Runnable() {
public void run() {
updateTorrentList();
setupRefreshTimer();
}
};
// Read all the user preferences
readSettings();
// Setup the default server daemon
setupDaemon();
// Set up a task queue
queue = new TaskQueue(new TaskResultHandler(this));
queue.start();
// Start the alarm service, if needed
BootReceiver.startAlarm(getActivity().getApplicationContext());
// Check for new app version, if needed
BootReceiver.startUpdateCheck(getActivity().getApplicationContext());
handleIntent(getActivity().getIntent());
}
public void handleIntent(final Intent startIntent) {
// Handle new intents that come from either a regular application startup, a startup from a
// new intent or a new intent being send with the application already started
if (startIntent != null && (startIntent.getData() != null ||
(startIntent.getAction() != null && startIntent.getAction().equals(Transdroid.INTENT_ADD_MULTIPLE))) &&
!isLaunchedFromHistory(startIntent)) {
if (startIntent.getAction() != null && startIntent.getAction().equals(Transdroid.INTENT_ADD_MULTIPLE)) {
// Intent should have some extras pointing to possibly multiple torrents
String[] urls = startIntent.getStringArrayExtra(Transdroid.INTENT_TORRENT_URLS);
String[] titles = startIntent.getStringArrayExtra(Transdroid.INTENT_TORRENT_TITLES);
if (urls != null) {
for (int i = 0; i < urls.length; i++) {
addTorrentByUrl(urls[i], (titles != null && titles.length >= i? titles[i]: "Torrent"));
}
}
} else {
// Intent should have some Uri data pointing to a single torrent
String data = startIntent.getDataString();
if (data != null && startIntent.getData() != null && startIntent.getData().getScheme() != null) {
// From Android 4.2 the file path is not directly in the Intent :( but rather in the 'Download manager' cursor
if (startIntent.getData().getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
addTorrentFromDownloads(startIntent.getData());
} else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_HTTP)
|| startIntent.getData().getScheme().equals(HttpHelper.SCHEME_HTTPS)) {
// From a global intent to add a .torrent file via URL (maybe form the browser)
String title = data.substring(data.lastIndexOf("/"));
if (startIntent.hasExtra(Transdroid.INTENT_TORRENT_TITLE)) {
title = startIntent.getStringExtra(Transdroid.INTENT_TORRENT_TITLE);
}
addTorrentByUrl(data, title);
} else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_MAGNET)) {
// From a global intent to add a magnet link via URL (usually from the browser)
addTorrentByMagnetUrl(data);
} else if (startIntent.getData().getScheme().equals(HttpHelper.SCHEME_FILE)) {
// From a global intent to add via the contents of a local .torrent file (maybe form a file manager)
addTorrentByFile(data);
}
}
}
}
// Possibly switch to a specific daemon (other than the last used)
boolean forceUpdate = false;
if (startIntent != null && !isLaunchedFromHistory(startIntent) &&
startIntent.hasExtra(Transdroid.INTENT_OPENDAEMON)) {
String openDaemon = startIntent.getStringExtra(Transdroid.INTENT_OPENDAEMON);
if (!daemon.getSettings().getIdString().equals(openDaemon)) {
int openDaemonI = (openDaemon == null || openDaemon.equals("")? 0: Integer.parseInt(openDaemon));
if (openDaemonI >= allDaemonSettings.size()) {
openDaemonI = 0;
}
forceUpdate = true;
switchDaemonConfig(openDaemonI);
}
}
if (forceUpdate || allTorrents == null) {
// Not swithcing to another daemon and no known list of torrents: update
updateTorrentList();
} else {
// We retained the list of torrents form the fragment state: show again
updateStatusText(null);
updateTorrentsView(false);
}
}
private boolean isLaunchedFromHistory(final Intent startIntent) {
return (startIntent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0;
}
public void onResume() {
super.onResume();
queue.start();
setupRefreshTimer();
}
public void onPause() {
super.onPause();
queue.requestStop();
handler.removeCallbacks(refreshRunable);
}
/**
* Start a refresh timer, if the user enabled this in the settings
*/
private void setupRefreshTimer() {
if (interfaceSettings != null && interfaceSettings.getRefreshTimerInterval() > 0) {
handler.postDelayed(refreshRunable, interfaceSettings.getRefreshTimerInterval() * 1000);
}
}
private void readSettings() {
TLog.d(LOG_NAME, "Reading settings");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
allDaemonSettings = Preferences.readAllDaemonSettings(prefs);
lastUsedDaemonSettings = Preferences.readLastUsedDaemonOrderNumber(prefs, allDaemonSettings);
interfaceSettings = Preferences.readInterfaceSettings(prefs);
sortSetting = TorrentsSortBy.getStatus(prefs.getInt(Preferences.KEY_PREF_LASTSORTBY, TorrentsSortBy.Alphanumeric.getCode()));
sortReversed = prefs.getBoolean(Preferences.KEY_PREF_LASTSORTORD, false);
onlyShowTransferring = prefs.getBoolean(Preferences.KEY_PREF_LASTSORTGTZERO, false);
alarmServiceSettings = Preferences.readAlarmSettings(prefs);
// Update the navigation list of the action bar
ignoreFirstListNavigation = true;
getSherlockActivity().getSupportActionBar().setListNavigationCallbacks(buildServerListAdapter(), onServerChanged );
}
private void setupDaemon() {
// If preferences are set, create the daemon adapter
if (allDaemonSettings != null && allDaemonSettings.size() > lastUsedDaemonSettings &&
allDaemonSettings.get(lastUsedDaemonSettings) != null && allDaemonSettings.get(lastUsedDaemonSettings).getType() != null) {
// Instantiate the daemon (the connection isn't made until an actual request is done)
DaemonSettings settings = allDaemonSettings.get(lastUsedDaemonSettings);
daemon = settings.getType().createAdapter(settings);
emptyText.setText(R.string.connecting);
// Show which server configuration is currently active
ignoreFirstListNavigation = true;
getSherlockActivity().getSupportActionBar().setSelectedNavigationItem(lastUsedDaemonSettings);
// Show the control bar
startsettings.setVisibility(View.GONE);
controlbar.setVisibility(View.VISIBLE);
statusBox.setVisibility(View.GONE);
activeLabel = null;
inAlternativeMode = false; // TODO: Actually this should be retrieved from the server's session
getSherlockActivity().supportInvalidateOptionsMenu();
} else {
daemon = null;
// The 'set preferences first' screen is shown
emptyText.setText(R.string.no_settings);
// Show that no server configuration is currently active
ignoreFirstListNavigation = true;
getSherlockActivity().getSupportActionBar().setListNavigationCallbacks(null, onServerChanged);
statusBox.setVisibility(View.GONE);
viewtype.setText("");
// Hide the control bar
startsettings.setVisibility(View.VISIBLE);
controlbar.setVisibility(View.GONE);
activeLabel = null;
getSherlockActivity().supportInvalidateOptionsMenu();
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Add the pause/resume/stop/start options
Torrent selected = (Torrent) getTorrentListAdapter().getItem((int) ((AdapterContextMenuInfo)menuInfo).id);
if (selected.canPause()) {
menu.add(0, MENU_PAUSE_ID, 0, R.string.menu_pause);
} else if (selected.canResume()) {
menu.add(0, MENU_RESUME_ID, 0, R.string.menu_resume);
}
if (daemon != null && Daemon.supportsStoppingStarting(daemon.getType())) {
if (selected.canStop()) {
menu.add(0, MENU_STOP_ID, 0, R.string.menu_stop);
} else if (selected.canStart()) {
menu.add(0, MENU_START_ID, 0, R.string.menu_start);
}
}
if (daemon != null && Daemon.supportsForcedStarting(daemon.getType()) && selected.canStart()) {
menu.add(0, MENU_FORCESTART_ID, 0, R.string.menu_forcestart);
}
// Add the remove options
menu.add(0, MENU_REMOVE_ID, 0, R.string.menu_remove);
if (daemon != null && Daemon.supportsRemoveWithData(daemon.getType())) {
menu.add(0, MENU_REMOVE_DATA_ID, 0, R.string.menu_remove_data);
}
// Add the 'set label' option
if (daemon != null && Daemon.supportsSetLabel(daemon.getType())) {
menu.add(0, MENU_SETLABEL_ID, 0, R.string.menu_setlabel);
}
// Add the 'set download location' option
if (daemon != null && Daemon.supportsSetDownloadLocation(daemon.getType())) {
menu.add(0, MENU_SETDOWNLOADLOCATION_ID, 0, R.string.menu_setdownloadlocation);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Add title bar buttons
MenuItem miRefresh = menu.add(0, MENU_REFRESH_ID, 0, R.string.refresh);
miRefresh.setIcon(R.drawable.icon_refresh_title);
miRefresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
if (inProgress) {
// Show progress spinner instead of the option item
View view = getActivity().getLayoutInflater().inflate(R.layout.part_actionbar_progressitem, null);
miRefresh.setActionView(view);
}
MenuItem miSearch = menu.add(0, MENU_SEARCH_ID, 0, R.string.search);
miSearch.setIcon(R.drawable.icon_search_title);
miSearch.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
MenuItem miAltMode = menu.add(0, MENU_ALTMODE_ID, 0, R.string.menu_altmode);
miAltMode.setIcon(inAlternativeMode? R.drawable.icon_turtle_title: R.drawable.icon_turtle_title_off);
miAltMode.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
miAltMode.setVisible(daemon != null && Daemon.supportsSetAlternativeMode(daemon.getType()));
// Add the menu options row 1
MenuItem miAdd = menu.add(0, MENU_ADD_ID, 0, R.string.menu_add);
if (useTabletInterface) {
miAdd.setIcon(R.drawable.icon_add);
} else {
miAdd.setIcon(android.R.drawable.ic_menu_add);
}
miAdd.setShortcut('1', 'a');
miAdd.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
MenuItem miBarcode = menu.add(0, MENU_BARCODE_ID, 0, R.string.menu_scanbarcode);
miBarcode.setIcon(R.drawable.icon_barcode);
miBarcode.setShortcut('2', 'f');
miBarcode.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
MenuItem miRss = menu.add(0, MENU_RSS_ID, 0, R.string.menu_rss);
miRss.setIcon(R.drawable.icon_rss);
miRss.setShortcut('3', 'r');
miRss.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
// Add the menu options row 2
SubMenu miForAll = menu.addSubMenu(MENU_FORALL_GROUP_ID, MENU_FORALL_ID, 0, R.string.menu_forall);
miForAll.setIcon(android.R.drawable.ic_menu_set_as);
miForAll.add(MENU_FORALL_GROUP_ID, MENU_FORALL_PAUSE_ID, 0, R.string.menu_forall_pause).setShortcut('4', 'p');
miForAll.add(MENU_FORALL_GROUP_ID, MENU_FORALL_RESUME_ID, 0, R.string.menu_forall_resume).setShortcut('5', 'u');
miForAll.add(MENU_FORALL_GROUP_ID, MENU_FORALL_STOP_ID, 0, R.string.menu_forall_stop).setShortcut('7', 't');
miForAll.add(MENU_FORALL_GROUP_ID, MENU_FORALL_START_ID, 0, R.string.menu_forall_start).setShortcut('8', 's');
menu.add(0, MENU_FILTER_ID, 0, R.string.menu_filter);
SubMenu miSort = menu.addSubMenu(MENU_SORT_GROUP_ID, MENU_SORT_ID, 0, R.string.menu_sort);
miSort.setIcon(android.R.drawable.ic_menu_sort_alphabetically);
//miSort.setHeaderTitle(R.string.menu_sort_reverse);
miSort.add(MENU_SORT_GROUP_ID, MENU_SORT_ALPHA_ID, 0, R.string.menu_sort_alpha).setAlphabeticShortcut('1').setChecked(true);
miSort.add(MENU_SORT_GROUP_ID, MENU_SORT_STATUS_ID, 0, R.string.menu_sort_status).setAlphabeticShortcut('2');
miSort.add(MENU_SORT_GROUP_ID, MENU_SORT_ADDED_ID, 0, R.string.menu_sort_added).setAlphabeticShortcut('3');
miSort.add(MENU_SORT_GROUP_ID, MENU_SORT_DONE_ID, 0, R.string.menu_sort_done).setAlphabeticShortcut('4');
miSort.add(MENU_SORT_GROUP_ID, MENU_SORT_UPSPEED_ID, 0, R.string.menu_sort_upspeed).setAlphabeticShortcut('5');
miSort.add(MENU_SORT_GROUP_ID, MENU_SORT_RATIO_ID, 0, R.string.menu_sort_ratio).setAlphabeticShortcut('6');
miSort.setGroupCheckable(MENU_SORT_GROUP_ID, true, true);
miSort.add(MENU_SORT_GTZERO_ID, MENU_SORT_GTZERO_ID, 0, R.string.menu_sort_onlytransferring).setCheckable(true);
// Add the extras menu options
MenuItem miSpeeds = menu.add(0, MENU_RATES_ID, 0, R.string.menu_speeds);
miSpeeds.setNumericShortcut('6');
miSpeeds.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
MenuItem miSwitch = menu.add(0, MENU_SWITCH_ID, 0, R.string.menu_servers);
miSwitch.setShortcut('9', 'h');
miSwitch.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add(0, MENU_ERRORREPORT_ID, 0, R.string.menu_errorreport);
menu.add(0, MENU_CHANGELOG_ID, 0, R.string.menu_changelog);
MenuItem miSettings = menu.add(0, MENU_SETTINGS_ID, 0, R.string.menu_settings);
//miSettings.setIcon(android.R.drawable.ic_menu_preferences);
miSettings.setNumericShortcut('0');
miSettings.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
boolean ok = daemon != null;
menu.findItem(MENU_ADD_ID).setEnabled(ok);
menu.findItem(MENU_BARCODE_ID).setEnabled(ok);
menu.findItem(MENU_RSS_ID).setEnabled(ok);
menu.findItem(MENU_FORALL_ID).setEnabled(ok);
menu.findItem(MENU_FILTER_ID).setEnabled(ok);
menu.findItem(MENU_SORT_ID).setEnabled(ok);
if (ok) {
menu.findItem(MENU_ALTMODE_ID).setVisible(Daemon.supportsSetAlternativeMode(daemon.getType()));
/*menu.findItem(MENU_SORT_ADDED_ID).setVisible(Daemon.supportsDateAdded(daemon.getType()));
menu.findItem(MENU_FORALL_STOP_ID).setVisible(Daemon.supportsStoppingStarting(daemon.getType()));
menu.findItem(MENU_FORALL_START_ID).setVisible(Daemon.supportsStoppingStarting(daemon.getType()));
// Show the currently selected sort by option
SubMenu sortmenu = menu.findItem(MENU_SORT_ID).getSubMenu();
for (int i = 0; i < sortmenu.size(); i++) {
if (sortmenu.getItem(i).getItemId() == MENU_SORT_ALPHA_ID && sortSetting == TorrentsSortBy.Alphanumeric) {
sortmenu.getItem(i).setChecked(true);
break;
} else if (sortmenu.getItem(i).getItemId() == MENU_SORT_STATUS_ID && sortSetting == TorrentsSortBy.Status) {
sortmenu.getItem(i).setChecked(true);
break;
} else if (sortmenu.getItem(i).getItemId() == MENU_SORT_ADDED_ID && sortSetting == TorrentsSortBy.DateAdded) {
sortmenu.getItem(i).setChecked(true);
break;
} else if (sortmenu.getItem(i).getItemId() == MENU_SORT_DONE_ID && sortSetting == TorrentsSortBy.DateDone) {
sortmenu.getItem(i).setChecked(true);
break;
} else if (sortmenu.getItem(i).getItemId() == MENU_SORT_UPSPEED_ID && sortSetting == TorrentsSortBy.UploadSpeed) {
sortmenu.getItem(i).setChecked(true);
break;
} else if (sortmenu.getItem(i).getItemId() == MENU_SORT_RATIO_ID && sortSetting == TorrentsSortBy.Ratio) {
sortmenu.getItem(i).setChecked(true);
break;
}
}
// Show the checkbox status according to the current settings
menu.findItem(MENU_SORT_GTZERO_ID).setChecked(onlyShowTransferring);*/
}
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if (daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return true;
}
// Get torrent item (if it still exists)
if (getTorrentListAdapter().getCount() <= info.id)
return true;
Torrent selection = (Torrent) getTorrentListAdapter().getItem((int)info.id);
switch (item.getItemId()) {
case MENU_PAUSE_ID:
// Set an intermediate status first (for a response feel)
selection.mimicPause();
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(PauseTask.create(daemon, selection));
return true;
case MENU_RESUME_ID:
// Set an intermediate status first (for a response feel)
selection.mimicResume();
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(ResumeTask.create(daemon, selection));
queue.enqueue(RetrieveTask.create(daemon));
return true;
case MENU_STOP_ID:
// Set an intermediate status first (for a response feel)
selection.mimicStop();
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(StopTask.create(daemon, selection));
return true;
case MENU_START_ID:
// Set an intermediate status first (for a response feel)
selection.mimicStart();
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(StartTask.create(daemon, selection, false));
queue.enqueue(RetrieveTask.create(daemon));
return true;
case MENU_FORCESTART_ID:
// Set an intermediate status first (for a response feel)
selection.mimicStart();
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(StartTask.create(daemon, selection, true));
queue.enqueue(RetrieveTask.create(daemon));
return true;
case MENU_REMOVE_ID:
if (interfaceSettings.getAskBeforeRemove()) {
// We store the torrent that we selected so the dialog can use this to make its calls
selectedTorrent = selection;
selectedRemoveData = false;
showDialog(DIALOG_ASKREMOVE);
} else {
removeTorrentOnServer(selection, false);
}
return true;
case MENU_REMOVE_DATA_ID:
if (interfaceSettings.getAskBeforeRemove()) {
// We store the torrent that we selected so the dialog can use this to make its calls
selectedTorrent = selection;
selectedRemoveData = true;
showDialog(DIALOG_ASKREMOVE);
} else {
removeTorrentOnServer(selection, true);
}
return true;
case MENU_SETLABEL_ID:
// Store the torrent that we selected and open the set label dialog
selectedTorrent = selection;
showDialog(DIALOG_SETLABEL);
return true;
case MENU_SETDOWNLOADLOCATION_ID:
// Store the torrent that we selected and open the set download location dialog
selectedTorrent = selection;
showDialog(DIALOG_SETDOWNLOADLOCATION);
return true;
}
return super.onContextItemSelected(item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Check connection first (when not opening the settings)
if (item.getItemId() != MENU_SETTINGS_ID &&
item.getItemId() != MENU_CHANGELOG_ID && daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return true;
}
switch (item.getItemId()) {
/*case android.R.id.home:
// Home button click in the action bar
Intent i = new Intent(getActivity(), Torrents.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;*/
case MENU_REFRESH_ID:
refreshActivity();
break;
case MENU_SEARCH_ID:
getSherlockActivity().onSearchRequested();
break;
case MENU_ALTMODE_ID:
switchAlternativeMode();
break;
case MENU_FORALL_PAUSE_ID:
if (allTorrents != null && allTorrents.size() > 0) {
// Set an intermediate status first on all items (for a response feel)
for (Torrent torrent : allTorrents) {
torrent.mimicPause();
}
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(PauseAllTask.create(daemon));
}
break;
case MENU_FORALL_RESUME_ID:
if (allTorrents != null && allTorrents.size() > 0) {
// Set an intermediate status first on all items (for a response feel)
for (Torrent torrent : allTorrents) {
torrent.mimicResume();
}
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(ResumeAllTask.create(daemon));
queue.enqueue(RetrieveTask.create(daemon));
}
break;
case MENU_FORALL_STOP_ID:
if (allTorrents != null && allTorrents.size() > 0 && Daemon.supportsStoppingStarting(daemon.getType())) {
// Set an intermediate status first on all items (for a response feel)
for (Torrent torrent : allTorrents) {
torrent.mimicStop();
}
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(StopAllTask.create(daemon));
}
break;
case MENU_FORALL_START_ID:
if (allTorrents != null && allTorrents.size() > 0 && Daemon.supportsStoppingStarting(daemon.getType())) {
// Set an intermediate status first on all items (for a response feel)
for (Torrent torrent : allTorrents) {
torrent.mimicStart();
}
// Update adapter
getTorrentListAdapter().notifyDataSetChanged();
queue.enqueue(StartAllTask.create(daemon, false));
queue.enqueue(RetrieveTask.create(daemon));
}
break;
case MENU_ADD_ID:
// Show a torrent URL input screen;
startActivity(new Intent(getActivity(), Add.class));
break;
case MENU_BARCODE_ID:
startBarcodeScanner();
break;
case MENU_RSS_ID:
// Show the RSS feeds screen
startActivity(new Intent(getActivity(), RssFeeds.class));
break;
case MENU_SWITCH_ID:
// Present a dialog with all available servers
showDialog(DIALOG_SERVERS);
break;
case MENU_SETTINGS_ID:
// Open settings menu
startActivityForResult(new Intent(getActivity(), PreferencesMain.class), ACTIVITY_PREFERENCES);
break;
case MENU_RATES_ID:
// Present a dialog that allows the setting of maxium transfer rates
showDialog(DIALOG_RATES);
break;
case MENU_CHANGELOG_ID:
// Present a dialog that shows version information and recent changes
showDialog(DIALOG_CHANGELOG);
break;
case MENU_ERRORREPORT_ID:
ErrorLogSender.collectAndSendLog(getActivity(), daemon, allDaemonSettings.get(lastUsedDaemonSettings));
break;
case MENU_FILTER_ID:
// Present a dialog that allows filtering the list
showDialog(DIALOG_FILTER);
break;
case MENU_SORT_ALPHA_ID:
// Resort
item.setChecked(true);
newTorrentListSorting(TorrentsSortBy.Alphanumeric);
break;
case MENU_SORT_STATUS_ID:
// Resort
item.setChecked(true);
newTorrentListSorting(TorrentsSortBy.Status);
break;
case MENU_SORT_DONE_ID:
// Resort
item.setChecked(true);
newTorrentListSorting(TorrentsSortBy.DateDone);
break;
case MENU_SORT_UPSPEED_ID:
// Resort
item.setChecked(true);
newTorrentListSorting(TorrentsSortBy.UploadSpeed);
break;
case MENU_SORT_RATIO_ID:
// Resort
item.setChecked(true);
newTorrentListSorting(TorrentsSortBy.Ratio);
break;
case MENU_SORT_ADDED_ID:
if (Daemon.supportsDateAdded(daemon.getType())) {
// Resort
item.setChecked(true);
newTorrentListSorting(TorrentsSortBy.DateAdded);
}
break;
case MENU_SORT_GTZERO_ID:
// Set boolean to filter on only transferring (> 0 KB/s) torrents
item.setChecked(!item.isChecked());
onlyShowTransferring = item.isChecked();
updateTorrentsView(true);
break;
}
return super.onOptionsItemSelected(item);
}
private OnItemClickListener onTorrentClicked = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (getTorrentListAdapter() != null) {
Torrent tor = getTorrentListAdapter().getItem(position);
// Show the details in the right of the screen (tablet interface) or separately
if (useTabletInterface) {
FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.details, new DetailsFragment(TorrentsFragment.this, lastUsedDaemonSettings, tor,
buildLabelTexts(false)));
ft.commit();
} else {
Intent i = new Intent(getActivity(), Details.class);
i.putExtra(Details.STATE_DAEMON, lastUsedDaemonSettings);
i.putExtra(Details.STATE_LABELS, buildLabelTexts(false));
i.putExtra(Details.STATE_TORRENT, tor);
startActivityForResult(i, ACTIVITY_DETAILS);
}
}
}
};
private void startBarcodeScanner() {
// Test to see if the ZXing barcode scanner is available that can handle the SCAN intent
Intent scan = new Intent(Transdroid.SCAN_INTENT);
scan.addCategory(Intent.CATEGORY_DEFAULT);
if (ActivityUtil.isIntentAvailable(getActivity(), scan)) {
// Ask the barcode scanner to allow the user to scan some code
startActivityForResult(scan, ACTIVITY_BARCODE);
} else {
// Show a message if the user should install the barcode scanner for this feature
showDialog(DIALOG_INSTALLBARCODESCANNER);
}
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SERVERS:
// Build a dialog with a radio box per daemon configuration
AlertDialog.Builder serverDialog = new AlertDialog.Builder(getActivity());
serverDialog.setTitle(R.string.menu_servers);
serverDialog.setSingleChoiceItems(
buildServerTextsForDialog(), // The strings of the available server configurations
(lastUsedDaemonSettings < allDaemonSettings.size()? lastUsedDaemonSettings: 0), // The current selection except when this suddenly doesn't exist any more
new DialogInterface.OnClickListener() {
@Override
// When the server is clicked (and it is different from the current active configuration),
// reload the daemon and update the torrent list
public void onClick(DialogInterface dialog, int which) {
if (which != lastUsedDaemonSettings) {
switchDaemonConfig(which);
}
dismissDialog(DIALOG_SERVERS);
}
});
return serverDialog.create();
case DIALOG_REFRESH_INTERVAL:
// Build a dialog with a radio boxes of different refresh intervals to choose from
AlertDialog.Builder refintDialog = new AlertDialog.Builder(getActivity());
refintDialog.setTitle(R.string.pref_uirefresh);
refintDialog.setSingleChoiceItems(
R.array.pref_uirefresh_types,
getCurrentRefreshIntervalID(),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Store new refresh interval
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Preferences.storeNewRefreshInterval(prefs,
getResources().getStringArray(R.array.pref_uirefresh_values)[which]);
interfaceSettings = Preferences.readInterfaceSettings(prefs);
// Apply new refresh interval
handler.removeCallbacks(refreshRunable); // Stops refresh timer
setupRefreshTimer();
dismissDialog(DIALOG_REFRESH_INTERVAL);
}
});
return refintDialog.create();
case DIALOG_SETLABEL:
// Build a dialog that asks for a new or selected an existing label to assign to the selected torrent
String[] setLabelTexts = buildLabelTexts(false);
SetLabelDialog setLabelDialog = new SetLabelDialog(getActivity(), new ResultListener() {
@Override
public void onLabelResult(String newLabel) {
if (newLabel.equals(getString(R.string.labels_unlabeled).toString())) {
// Setting a torrent to 'unlabeled' is actually setting the label to an empty string
newLabel = "";
}
setNewLabel(newLabel);
}
}, setLabelTexts, selectedTorrent.getLabelName());
setLabelDialog.setTitle(R.string.labels_newlabel);
return setLabelDialog;
case DIALOG_SETDOWNLOADLOCATION:
// Build a dialog that asks for a new download location for the torrent
final View setLocationLayout = getActivity().getLayoutInflater().inflate(R.layout.dialog_set_download_location, null);
final EditText newLocation = (EditText) setLocationLayout.findViewById(R.id.download_location);
newLocation.setText(selectedTorrent.getLocationDir());
AlertDialog.Builder setLocationDialog = new AlertDialog.Builder(getActivity());
setLocationDialog.setTitle(R.string.menu_setdownloadlocation);
setLocationDialog.setView(setLocationLayout);
setLocationDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
setDownloadLocation(newLocation.getText().toString());
}
});
setLocationDialog.setNegativeButton(android.R.string.cancel, null);
return setLocationDialog.create();
case DIALOG_RATES:
// Build a dialog that allows for the input of maximum upload and download transfer rates
final View ratesDialogView = getActivity().getLayoutInflater().inflate(R.layout.dialog_transfer_rates, null);
final EditText rateDownload = (EditText) ratesDialogView.findViewById(R.id.rate_download);
final EditText rateUpload = (EditText) ratesDialogView.findViewById(R.id.rate_upload);
AlertDialog.Builder ratesDialog = new AlertDialog.Builder(getActivity());
ratesDialog.setTitle(R.string.menu_speeds);
ratesDialog.setView(ratesDialogView);
ratesDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setTransferRates(
(rateUpload.getText().toString().equals("")? null: Integer.parseInt(rateUpload.getText().toString())),
(rateDownload.getText().toString().equals("")? null: Integer.parseInt(rateDownload.getText().toString())));
}
});
ratesDialog.setNeutralButton(R.string.rate_reset, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Reset the text boxes first
rateUpload.setText("");
rateDownload.setText("");
setTransferRates(null, null);
}
});
ratesDialog.setNegativeButton(android.R.string.cancel, null);
return ratesDialog.create();
case DIALOG_CHANGELOG:
// Build a dialog listing the recent changes in Transdroid
AlertDialog.Builder changesDialog = new AlertDialog.Builder(getActivity());
changesDialog.setTitle(R.string.menu_changelog);
View changes = getActivity().getLayoutInflater().inflate(R.layout.dialog_about, null);
((TextView)changes.findViewById(R.id.transdroid)).setText("Transdroid " + ActivityUtil.getVersionNumber(getActivity()));
changesDialog.setView(changes);
return changesDialog.create();
case DIALOG_ASKREMOVE:
// Build a dialog that asks to confirm the deletions of a torrent
AlertDialog.Builder askRemoveDialog = new AlertDialog.Builder(getActivity());
askRemoveDialog.setTitle(R.string.askremove_title);
askRemoveDialog.setMessage(R.string.askremove);
askRemoveDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
removeTorrentOnServer(selectedTorrent, selectedRemoveData);
dismissDialog(DIALOG_ASKREMOVE);
}
});
askRemoveDialog.setNegativeButton(android.R.string.no, null);
return askRemoveDialog.create();
case DIALOG_ADDFAILED:
// Build a dialog that asks to retry or store this torrent and add it later
AlertDialog.Builder addFailedDialog = new AlertDialog.Builder(getActivity());
addFailedDialog.setTitle(R.string.addfailed_title);
if (alarmServiceSettings.isAlarmEnabled()) {
addFailedDialog.setMessage(getString(R.string.addfailed_service2, failedTorrentTitle));
addFailedDialog.setNeutralButton(R.string.addfailed_addlater, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Preferences.addToTorrentAddQueue(PreferenceManager.getDefaultSharedPreferences(getActivity()),
daemon.getSettings().getIdString(), failedTorrentUri);
dismissDialog(DIALOG_ADDFAILED);
}
});
} else {
addFailedDialog.setMessage(getString(R.string.addfailed_noservice2, failedTorrentTitle));
}
addFailedDialog.setPositiveButton(R.string.addfailed_retry, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
if (Preferences.isQueuedTorrentToAddALocalFile(failedTorrentUri)) {
addTorrentByFile(failedTorrentUri);
} else if (Preferences.isQueuedTorrentToAddAMagnetUrl(failedTorrentUri)) {
addTorrentByMagnetUrl(failedTorrentUri);
} else {
addTorrentByUrl(failedTorrentUri, failedTorrentTitle);
}
dismissDialog(DIALOG_ADDFAILED);
}
});
addFailedDialog.setNegativeButton(android.R.string.no, null);
return addFailedDialog.create();
case DIALOG_INSTALLBARCODESCANNER:
return ActivityUtil.buildInstallDialog(getActivity(), R.string.scanner_not_found, Transdroid.SCANNER_MARKET_URI);
case DIALOG_FILTER:
// Build a dialog that asks for a new download location for the torrent
final View setFilterLayout = getActivity().getLayoutInflater().inflate(R.layout.dialog_set_filter, null);
final EditText newFilter = (EditText) setFilterLayout.findViewById(R.id.filter);
if(activeFilter != null)
newFilter.setText(activeFilter);
AlertDialog.Builder setFilterDialog = new AlertDialog.Builder(getActivity());
setFilterDialog.setTitle(R.string.menu_setfilter);
setFilterDialog.setView(setFilterLayout);
setFilterDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
setFilter(newFilter.getText().toString());
}
});
setFilterDialog.setNegativeButton(android.R.string.cancel, null);
setFilterDialog.setNeutralButton(R.string.reset, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
setFilter("");
}
});
return setFilterDialog.create();
}
return null;
}
/*@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DIALOG_SERVERS:
// Re-populate the dialog adapter with possibly new/edited server configurations
AlertDialog serverDialog = (AlertDialog) dialog;
ListView serverRadios = serverDialog.getListView();
ArrayAdapter<String> serverList = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice, android.R.id.text1, buildServerTextsForDialog());
serverRadios.setAdapter(serverList);
// Also pre-select the active daemon
int serverSelected = (lastUsedDaemonSettings < allDaemonSettings.size()? lastUsedDaemonSettings: 0); // Prevent going out of bounds
serverRadios.clearChoices();
serverRadios.setItemChecked(serverSelected, true);
serverRadios.setSelection(serverSelected);
break;
case DIALOG_REFRESH_INTERVAL:
// Pre-select the current refresh interval
AlertDialog refintDialog = (AlertDialog) dialog;
ListView refintRadios = refintDialog.getListView();
refintRadios.clearChoices();
refintRadios.setItemChecked(getCurrentRefreshIntervalID(), true);
refintRadios.setSelection(getCurrentRefreshIntervalID());
break;
case DIALOG_SETLABEL:
// Re-populate the dialog adapter with the available labels
SetLabelDialog setLabelDialog = (SetLabelDialog) dialog;
String[] setLabelTexts = buildLabelTexts(false);
setLabelDialog.resetDialog(this, setLabelTexts, selectedTorrent.getLabelName());
break;
case DIALOG_SETDOWNLOADLOCATION:
// Show the existing download location
final EditText newLocation = (EditText) dialog.findViewById(R.id.download_location);
newLocation.setText(selectedTorrent.getLocationDir());
break;
case DIALOG_ADDFAILED:
AlertDialog addFailedDialog = (AlertDialog) dialog;
if (alarmServiceSettings.isAlarmEnabled()) {
addFailedDialog.setMessage(getString(R.string.addfailed_service2, failedTorrentTitle));
addFailedDialog.setButton2(getText(R.string.addfailed_addlater), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Preferences.addToTorrentAddQueue(PreferenceManager.getDefaultSharedPreferences(TorrentsFragment.this),
daemon.getSettings().getIdString(), failedTorrentUri);
removeDialog(DIALOG_ADDFAILED);
}
});
} else {
addFailedDialog.setMessage(getString(R.string.addfailed_noservice2, failedTorrentTitle));
addFailedDialog.setButton2(null, (DialogInterface.OnClickListener)null);
}
break;
}
}*/
private SpinnerAdapter buildServerListAdapter() {
ArrayAdapter<String> ad = new ArrayAdapter<String>(getActivity(), R.layout.abs__simple_spinner_item, buildServerTextsForDialog());
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return ad;
}
private String[] buildServerTextsForDialog() {
// Build a textual list of servers available
ArrayList<String> servers = new ArrayList<String>();
for (DaemonSettings daemon : allDaemonSettings) {
servers.add(daemon.getName());
}
return servers.toArray(new String[servers.size()]);
}
private int getCurrentRefreshIntervalID() {
String[] values = getResources().getStringArray(R.array.pref_uirefresh_values);
int current = interfaceSettings.getRefreshTimerInterval();
for (int i = 0; i < values.length; i++) {
if (values[i].equals(Integer.toString(current))) {
return i;
}
}
return 0;
}
private String[] buildLabelTexts(boolean addShowAll) {
// Build a textual list of used torrent labels
ArrayList<String> labelNames = new ArrayList<String>();
if (availableLabels != null) {
// The 'show all' label first ...
String showAll = getText(R.string.labels_showall).toString();
if (addShowAll) {
labelNames.add(showAll);
}
// ... then all the normal labels (which will end up in alphabetical order)
for (String name : availableLabels) {
if (!name.equals(showAll)) {
labelNames.add(name);
}
}
}
return labelNames.toArray(new String[labelNames.size()]);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ACTIVITY_PREFERENCES:
// Preference screen was called: use new preferences to connect
readSettings();
setupDaemon();
updateTorrentList();
break;
case ACTIVITY_DETAILS:
// Details screen was shown; we may have an updated torrent (it can be started/removed/etc.)
updateTorrentList();
break;
case ACTIVITY_BARCODE:
if (resultCode == Activity.RESULT_OK) {
// Get scan results code
String contents = data.getStringExtra("SCAN_RESULT");
String formatName = data.getStringExtra("SCAN_RESULT_FORMAT");
if (formatName != null && formatName.equals(Transdroid.SCAN_FORMAT_QRCODE)) {
// Scanned barcode was a QR code: assume the contents contain a URL to a .torrent file
TLog.d(LOG_NAME, "Add torrent from QR code url '" + contents + "'");
addTorrentByUrl(contents, "Torrent QR code"); // No real torrent title known
} else {
// Get a meaningful search query based on a Google Search product lookup
TLog.d(LOG_NAME, "Starting barcode lookup for code '" + contents + "' " + (formatName == null? "(code type is unknown)": "(this should be a " + formatName + " code)"));
setProgressBar(true);
new GoogleWebSearchBarcodeResolver() {
@Override
protected void onBarcodeLookupComplete(String result) {
setProgressBar(false);
// No proper result?
if (result == null || result.equals("")) {
TLog.d(LOG_NAME, "Barcode not resolved (timout, connection error, no items, etc.)");
Toast.makeText(getActivity(), R.string.no_results, Toast.LENGTH_SHORT).show();
return;
}
// Open TransdroidSearch directly, mimicking a search query
TLog.d(LOG_NAME, "Barcode resolved to '" + result + "'. Now starting search.");
Intent search = new Intent(getActivity(), Search.class);
search.setAction(Intent.ACTION_SEARCH);
search.putExtra(SearchManager.QUERY, result);
startActivity(search);
}
}.execute(contents);
}
}
break;
}
}
private void refreshActivity() {
updateTorrentList();
if (getSherlockActivity().getSupportFragmentManager().findFragmentById(R.id.details) != null) {
// Marshal the refresh button click to the fragment
((DetailsFragment)getSherlockActivity().getSupportFragmentManager().findFragmentById(R.id.details)).refreshActivity();
}
}
public void updateTorrentList() {
if (daemon != null) {
queue.enqueue(RetrieveTask.create(daemon));
if (Daemon.supportsStats(daemon.getType())) {
queue.enqueue(GetStatsTask.create(daemon));
}
}
}
private void addTorrentByUrl(String url, String title) {
if (daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return;
}
queue.enqueue(AddByUrlTask.create(daemon, url, title));
queue.enqueue(RetrieveTask.create(daemon));
}
private void addTorrentByMagnetUrl(String url) {
if (daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return;
}
if (!Daemon.supportsAddByMagnetUrl(daemon.getType())) {
// Not supported by the torrent client
Toast.makeText(getActivity(), R.string.no_magnet_links, Toast.LENGTH_SHORT).show();
return;
}
queue.enqueue(AddByMagnetUrlTask.create(daemon, url));
queue.enqueue(RetrieveTask.create(daemon));
}
private void addTorrentFromDownloads(Uri contentUri) {
InputStream input = null;
try {
// Open the content uri as input stream
input = getActivity().getContentResolver().openInputStream(contentUri);
// Write a temporary file with the torrent contents
File tempFile = File.createTempFile("transdroid_", ".torrent", getActivity().getCacheDir());
FileOutputStream output = new FileOutputStream(tempFile);
try {
final byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
addTorrentByFile(Uri.fromFile(tempFile).toString());
} finally {
output.close();
}
} catch (SecurityException e) {
// No longer access to this file
Toast.makeText(getActivity(), R.string.error_torrentfile, Toast.LENGTH_SHORT).show();
} catch (IOException e1) {
// Can't write temporary file
Toast.makeText(getActivity(), R.string.error_torrentfile, Toast.LENGTH_SHORT).show();
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
Toast.makeText(getActivity(), R.string.error_torrentfile, Toast.LENGTH_SHORT).show();
}
}
}
private void addTorrentByFile(String fileUri) {
if (daemon == null) {
// No connection possible yet: give message
if (getActivity() != null) {
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
}
return;
}
if (!Daemon.supportsAddByFile(daemon.getType())) {
// The daemon type does not support .torrent file uploads/metadata sending or this is not yet implemented
if (getActivity() != null) {
Toast.makeText(getActivity(), R.string.no_file_uploads, Toast.LENGTH_LONG).show();
}
return;
}
queue.enqueue(AddByFileTask.create(daemon, fileUri));
queue.enqueue(RetrieveTask.create(daemon));
}
private void removeTorrentOnServer(Torrent torrent, boolean removeData) {
// Remove the list item first (for a responsive feel) from views and labels
getTorrentListAdapter().remove(torrent);
updateEmptyListDescription();
// Remove the torrent from the server
queue.enqueue(RemoveTask.create(daemon, torrent, removeData));
}
private void setTransferRates(Integer uploadRate, Integer downloadRate) {
if (daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return;
}
if (!Daemon.supportsSetTransferRates(daemon.getType())) {
// The daemon type does not support adjusting the maximum transfer rates
Toast.makeText(getActivity(), R.string.rate_no_support, Toast.LENGTH_LONG).show();
return;
}
queue.enqueue(SetTransferRatesTask.create(daemon, uploadRate, downloadRate));
}
private void setNewLabel(String newLabel) {
if (daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return;
}
if (!Daemon.supportsSetLabel(daemon.getType())) {
// The daemon type does not support setting the label of a torrent
Toast.makeText(getActivity(), R.string.labels_no_support, Toast.LENGTH_LONG).show();
return;
}
// Mimic that we have already set the label (for a response feel)
selectedTorrent.mimicNewLabel(newLabel);
queue.enqueue(SetLabelTask.create(daemon, selectedTorrent, newLabel));
queue.enqueue(RetrieveTask.create(daemon));
}
private void setDownloadLocation(String newLocation) {
if (daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return;
}
if (!Daemon.supportsSetDownloadLocation(daemon.getType())) {
return;
}
queue.enqueue(SetDownloadLocationTask.create(daemon, selectedTorrent, newLocation));
}
protected void switchAlternativeMode() {
if (daemon == null) {
// No connection possible yet: give message
Toast.makeText(getActivity(), R.string.no_settings_short, Toast.LENGTH_SHORT).show();
return;
}
if (!Daemon.supportsSetAlternativeMode(daemon.getType())) {
return;
}
inAlternativeMode = !inAlternativeMode;
updateAlternativeModeIcon();
queue.enqueue(SetAlternativeModeTask.create(daemon, inAlternativeMode));
}
@Override
public void onQueuedTaskFinished(DaemonTask started) {
// Show the daemon status (speeds) again
updateStatusText(null);
}
@Override
public void onQueuedTaskStarted(DaemonTask started) {
// Started on a new task: turn on status indicator
setProgressBar(true);
// Show which task we are executing
updateStatusText(getStatusFromTask(started).toString());
}
@Override
public void onQueueEmpty() {
// No active task: turn off status indicator
setProgressBar(false);
}
private CharSequence getStatusFromTask(DaemonTask started) {
switch (started.getMethod()) {
case Retrieve:
return getText(R.string.task_refreshing);
case AddByUrl:
return getText(R.string.task_addbyurl);
case AddByMagnetUrl:
return getText(R.string.task_addbyurl);
case AddByFile:
return getText(R.string.task_addbyfile);
case Remove:
return getText(R.string.task_removing);
case Pause:
return getText(R.string.task_pausing);
case PauseAll:
return getText(R.string.task_pausingall);
case Resume:
return getText(R.string.task_resuming);
case ResumeAll:
return getText(R.string.task_resumingall);
case Stop:
return getText(R.string.task_stopping);
case StopAll:
return getText(R.string.task_stoppingall);
case Start:
return getText(R.string.task_starting);
case StartAll:
return getText(R.string.task_startingall);
case GetFileList:
return getText(R.string.task_getfiles);
case SetFilePriorities:
return getText(R.string.task_setfileprop);
case SetTransferRates:
return getText(R.string.task_settransrates);
case SetLabel:
return getText(R.string.task_setlabel);
case SetDownloadLocation:
return getText(R.string.task_setlocation);
case SetAlternativeMode:
return getText(R.string.task_setalternativemode);
}
return "";
}
@Override
public boolean isAttached() {
return getActivity() != null;
}
@Override
public void onTaskFailure(DaemonTaskFailureResult result) {
if (result.getMethod() == DaemonMethod.Retrieve) {
// For retrieve tasks: Only bother if we still are still looking at the same daemon since the task was queued
if (result.getTask().getAdapterType() == daemon.getType()) {
// Show error message
Toast.makeText(getActivity(), LocalTorrent.getResourceForDaemonException(result.getException()), Toast.LENGTH_SHORT * 2).show();
}
} else if (result.getMethod() == DaemonMethod.AddByFile) {
// Failed adding a torrent? Ask to add this torrent later
failedTorrentUri = ((AddByFileTask)result.getTask()).getFile();
failedTorrentTitle = new File(failedTorrentUri).getName(); // Use filename as title
showDialog(DIALOG_ADDFAILED);
} else if (result.getMethod() == DaemonMethod.AddByUrl) {
// Failed adding a torrent? Ask to add this torrent later
failedTorrentUri = ((AddByUrlTask)result.getTask()).getUrl();
failedTorrentTitle = ((AddByUrlTask)result.getTask()).getTitle(); // Get title directly from task
showDialog(DIALOG_ADDFAILED);
} else if (result.getMethod() == DaemonMethod.AddByMagnetUrl) {
// Failed adding a torrent? Ask to add this torrent later
failedTorrentUri = ((AddByMagnetUrlTask)result.getTask()).getUrl();
failedTorrentTitle = "Torrent"; // No way to know the title here
showDialog(DIALOG_ADDFAILED);
} else {
// Show error message
Toast.makeText(getActivity(), LocalTorrent.getResourceForDaemonException(result.getException()), Toast.LENGTH_SHORT * 2).show();
}
}
@Override
public void onTaskSuccess(DaemonTaskSuccessResult result) {
switch (result.getMethod()) {
case AddByFile:
case AddByUrl:
// Show 'added' message
Toast.makeText(getActivity(), R.string.torrent_added, Toast.LENGTH_SHORT).show();
break;
case Retrieve:
// Only bother if we still are still looking at the same daemon since the task was queued
if (result.getTask().getAdapterType() == daemon.getType()) {
// Sort the new list of torrents
allTorrents = ((RetrieveTaskSuccessResult) result).getTorrents();
Collections.sort(allTorrents, new TorrentsComparator(daemon, sortSetting, sortReversed));
// Sort the new list of labels
allLabels = ((RetrieveTaskSuccessResult) result).getLabels();
// Show refreshed totals for this daemon
updateStatusText(null);
updateTorrentsView(false);
// Show 'refreshed' message unless we enabled the hide refresh message setting
if (!interfaceSettings.shouldHideRefreshMessage()) {
Toast.makeText(getActivity(), R.string.list_refreshed, Toast.LENGTH_SHORT).show();
}
}
break;
case GetStats:
// Only bother if we still are still looking at the same daemon since the task was queued
if (result.getTask().getAdapterType() == daemon.getType()) {
GetStatsTaskSuccessResult stats = (GetStatsTaskSuccessResult) result;
if (Daemon.supportsSetAlternativeMode(daemon.getType())) {
// Update the alternative/tutle mode indicator
inAlternativeMode = stats.isAlternativeModeEnabled();
updateAlternativeModeIcon();
}
}
break;
case Remove:
// Show 'removed' message
boolean includingData = ((RemoveTask)result.getTask()).includingData();
Toast.makeText(getActivity(), "'" + result.getTargetTorrent().getName() + "' " + getText(includingData? R.string.torrent_removed_with_data: R.string.torrent_removed), Toast.LENGTH_SHORT).show();
break;
case Resume:
// Show 'resumed' message
Toast.makeText(getActivity(), "'" + result.getTargetTorrent().getName() + "' " + getText(R.string.torrent_resumed), Toast.LENGTH_SHORT).show();
break;
case ResumeAll:
// Show 'resumed all' message
Toast.makeText(getActivity(), getText(R.string.torrent_resumed_all), Toast.LENGTH_SHORT).show();
break;
case Pause:
// Show 'paused' message
Toast.makeText(getActivity(), "'" + result.getTargetTorrent().getName() + "' " + getText(R.string.torrent_paused), Toast.LENGTH_SHORT).show();
break;
case PauseAll:
// Show 'paused all' message
Toast.makeText(getActivity(), getText(R.string.torrent_paused_all), Toast.LENGTH_SHORT).show();
break;
case Start:
// Show 'started' message
Toast.makeText(getActivity(), "'" + result.getTargetTorrent().getName() + "' " + getText(R.string.torrent_started), Toast.LENGTH_SHORT).show();
break;
case StartAll:
// Show 'started all' message
Toast.makeText(getActivity(), getText(R.string.torrent_started_all), Toast.LENGTH_SHORT).show();
break;
case Stop:
// Show 'stopped' message
Toast.makeText(getActivity(), "'" + result.getTargetTorrent().getName() + "' " + getText(R.string.torrent_stopped), Toast.LENGTH_SHORT).show();
break;
case StopAll:
// Show 'stopped all' message
Toast.makeText(getActivity(), getText(R.string.torrent_stopped_all), Toast.LENGTH_SHORT).show();
break;
case SetTransferRates:
// Show 'rates updated' message
Toast.makeText(getActivity(), R.string.rate_updated, Toast.LENGTH_SHORT).show();
break;
case SetDownloadLocation:
Toast.makeText(getActivity(), getString(R.string.torrent_locationset, ((SetDownloadLocationTask)result.getTask()).getNewLocation()), Toast.LENGTH_SHORT).show();
break;
case SetAlternativeMode:
// Updated the mode: now update the server stats to reflect the real new status (since the action might have been unsuccessful for some reason)
queue.enqueue(GetStatsTask.create(daemon));
break;
}
}
private void updateAlternativeModeIcon() {
// By invalidation the options menu it gets redrawn and the turtle icon gets updated
getSherlockActivity().supportInvalidateOptionsMenu();
}
/**
* Shows the proper text when the torrent list is empty
*/
private void updateEmptyListDescription() {
// Show empty text when no torrents exist any more
if (getTorrentListAdapter() != null && getTorrentListAdapter().getAllItems().size() == 0) {
if (activeMainView == MainViewType.OnlyDownloading) {
emptyText.setText(R.string.no_downloading_torrents);
} else if (activeMainView == MainViewType.OnlyUploading) {
emptyText.setText(R.string.no_uploading_torrents);
} else if (activeMainView == MainViewType.OnlyInactive) {
emptyText.setText(R.string.no_inactive_torrents);
} else if (activeMainView == MainViewType.OnlyActive) {
emptyText.setText(R.string.no_active_torrents);
} else {
emptyText.setText(R.string.no_torrents);
}
}
}
private void updateStatusText(String taskmessageText) {
if (taskmessageText != null || allTorrents == null) {
taskmessage.setText(taskmessageText);
taskmessage.setVisibility(View.VISIBLE);
statusBox.setVisibility(View.GONE);
if (allTorrents == null) {
emptyText.setVisibility(View.VISIBLE);
}
return;
}
// Keep totals
int downloading = 0;
int downloadingD = 0;
int downloadingU = 0;
int eta = -1;
int seeding = 0;
int seedingU = 0;
//int other = 0;
for (Torrent tor : allTorrents) {
if (tor.getStatusCode() == TorrentStatus.Downloading && (!onlyShowTransferring || tor.getRateDownload() > 0)) {
downloading++;
downloadingD += tor.getRateDownload();
downloadingU += tor.getRateUpload();
eta = Math.max(eta, tor.getEta());
} else if (tor.getStatusCode() == TorrentStatus.Seeding && (!onlyShowTransferring || tor.getRateUpload() > 0)) {
seeding++;
seedingU += tor.getRateUpload();
//} else {
// other++;
}
}
// Set text views
taskmessage.setVisibility(View.GONE);
statusBox.setVisibility(View.VISIBLE);
statusDown.setText(downloading + "\u2193");
statusUp.setText(seeding + "\u2191");
statusDownRate.setText(FileSizeConverter.getSize(downloadingD) + getString(R.string.status_persecond));
statusUpRate.setText(FileSizeConverter.getSize(downloadingU + seedingU) + getString(R.string.status_persecond));
emptyText.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
private void newTorrentListSorting(TorrentsSortBy newSortBy) {
this.sortReversed = (sortSetting == newSortBy? !sortReversed: false); // If the same is selected again, reverse the sort order
this.sortSetting = newSortBy;
if (!(getTorrentListAdapter() == null || getTorrentListAdapter().getCount() == 0)) {
// Sort the shown list of torrents using the new sortBy criteria
Collections.sort(allTorrents, new TorrentsComparator(daemon, sortSetting, sortReversed));
updateTorrentsView(true);
}
// Remember the new option by saving it to the user preferences (for a new Transdroid startup)
Editor editor = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();
editor.putInt(Preferences.KEY_PREF_LASTSORTBY, sortSetting.getCode());
editor.putBoolean(Preferences.KEY_PREF_LASTSORTORD, sortReversed);
editor.putBoolean(Preferences.KEY_PREF_LASTSORTGTZERO, onlyShowTransferring);
editor.commit();
}
private OnNavigationListener onServerChanged = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (!ignoreFirstListNavigation ) {
switchDaemonConfig((int) itemId);
}
ignoreFirstListNavigation = false;
return true;
}
};
/**
* Clear the screen and set up the new daemon (just as if we were clicking on a daemon in the pop-up menu)
* @param which To which daemon settings configuration to switch to (which must exist)
*/
private void switchDaemonConfig(int which) {
if (getActivity() == null) {
return;
}
// Store this new 'last used server'
Preferences.storeLastUsedDaemonSettings(getActivity().getApplicationContext(), which);
lastUsedDaemonSettings = which;
// Clear any old 'refresh' tasks from the queue
queue.clear(DaemonMethod.Retrieve);
// Hide the old torrents list and show that we are connecting again
if (allTorrents != null) {
allTorrents.clear();
}
if (getTorrentListAdapter() != null) {
getTorrentListAdapter().clear();
}
emptyText.setText(R.string.connecting);
// Clear the old details fragment
if (useTabletInterface) {
Fragment f = getSherlockActivity().getSupportFragmentManager().findFragmentById(R.id.details);
if (f != null) {
FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
ft.remove(f);
ft.commit();
}
}
// Reload server and update torrent list
setupDaemon();
updateTorrentList();
}
private void loadLabels() {
availableLabels = new ArrayList<String>();
if (Daemon.supportsLabels(getActiveDaemonType())) {
// Add a label that includes all torrents called 'show all'
String showAll = getText(R.string.labels_showall).toString();
availableLabels.add(showAll);
// Gather the used labels from the torrents
if (allLabels!=null){
for (Label lab : allLabels) {
String name = lab.getName();
// Start a new label if this name wasn't encountered yet
if (!availableLabels.contains(name)) {
availableLabels.add(name);
}
}
}
for (Torrent tor : allTorrents) {
// Force a label name (use 'unlabeled' if none is provided)
String name = tor.getLabelName();
if (name == null || name.equals("")) {
name = getText(R.string.labels_unlabeled).toString();
}
tor.mimicNewLabel(name);
// Start a new label if this name wasn't encountered yet
if (!availableLabels.contains(name)) {
availableLabels.add(name);
}
}
Collections.sort(availableLabels);
}
viewtypeselectorpopup.updateLabels(availableLabels);
}
private void updateTorrentsView(boolean forceScrollToTop) {
if (daemon != null && allTorrents != null) {
// Load the labels
String useLabel = null;
String showAllLabelsText = getText(R.string.labels_showall).toString();
loadLabels();
if (Daemon.supportsLabels(getActiveDaemonType())) {
useLabel = showAllLabelsText;
if (activeLabel != null && availableLabels.contains(activeLabel)) {
useLabel = activeLabel;
}
}
// Build a list of torrents that should be shown
List<Torrent> showTorrents = new ArrayList<Torrent>();
for (Torrent torrent : allTorrents) {
if (matchesLabel(torrent, useLabel, showAllLabelsText) && matchesStatus(torrent, activeMainView) && matchesFilter(torrent, activeFilter)) {
showTorrents.add(torrent);
}
}
if (getTorrentListAdapter() == null) {
setListAdapter(new TorrentListAdapter(this, showTorrents));
} else {
getTorrentListAdapter().replace(showTorrents);
}
// Scroll to the top of the list as well?
if (forceScrollToTop) {
getListView().setSelection(0);
}
updateEmptyListDescription();
// Update the torrents view type text
int mainViewTextID = activeMainView == MainViewType.OnlyDownloading? R.string.view_showdl:
(activeMainView == MainViewType.OnlyUploading? R.string.view_showul:
(activeMainView == MainViewType.OnlyInactive? R.string.view_showinactive:
(activeMainView == MainViewType.OnlyActive? R.string.view_showactive: R.string.view_showall)));
int mainViewDrawableID = activeMainView == MainViewType.OnlyDownloading? R.drawable.icon_showdl:
(activeMainView == MainViewType.OnlyUploading? R.drawable.icon_showup:
(activeMainView == MainViewType.OnlyInactive? R.drawable.icon_showinactive:
(activeMainView == MainViewType.OnlyActive? R.drawable.icon_showactive: R.drawable.icon_showall)));
viewtype.setText(getText(mainViewTextID).toString() + (Daemon.supportsLabels(getActiveDaemonType())? "\n" + useLabel: ""));
viewtypeselector.setImageResource(mainViewDrawableID);
}
}
private boolean matchesLabel(Torrent torrent, String matchLabel, String showAllLabelsText) {
if (Daemon.supportsLabels(getActiveDaemonType())) {
return matchLabel == null || matchLabel.equals(showAllLabelsText) || torrent.getLabelName().equals(matchLabel);
}
return true;
}
private boolean matchesStatus(Torrent torrent, MainViewType matchViewType) {
boolean isActivelyDownloading = torrent.getStatusCode() == TorrentStatus.Downloading && (!onlyShowTransferring || torrent.getRateDownload() > 0);
boolean isActivelySeeding = torrent.getStatusCode() == TorrentStatus.Seeding && (!onlyShowTransferring || torrent.getRateUpload() > 0);
return (matchViewType == MainViewType.ShowAll ||
(matchViewType == MainViewType.OnlyDownloading && isActivelyDownloading) ||
(matchViewType == MainViewType.OnlyUploading && isActivelySeeding)||
(matchViewType == MainViewType.OnlyActive && (isActivelySeeding || isActivelyDownloading))||
(matchViewType == MainViewType.OnlyInactive && !isActivelyDownloading && !isActivelySeeding));
}
private boolean matchesFilter(Torrent torrent, String matchSearchString) {
return ((matchSearchString == null? true : false) || (torrent.getName().toLowerCase().indexOf(matchSearchString.toLowerCase()) > -1));
}
private void setProgressBar(boolean b) {
inProgress = b;
if (getSherlockActivity() != null)
getSherlockActivity().supportInvalidateOptionsMenu();
}
protected View findViewById(int id) {
return getView().findViewById(id);
}
protected ListView getListView() {
return (ListView) findViewById(R.id.torrents);
}
private TorrentListAdapter getTorrentListAdapter() {
return (TorrentListAdapter) getListView().getAdapter();
}
private void setListAdapter(TorrentListAdapter torrentListAdapter) {
getListView().setAdapter(torrentListAdapter);
if (torrentListAdapter == null || torrentListAdapter.getCount() <= 0) {
emptyText.setVisibility(View.VISIBLE);
getListView().setVisibility(View.GONE);
} else {
emptyText.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
}
public void setFilter(String search_text){
if(search_text.equals(""))
activeFilter = null;
else
activeFilter = search_text.trim();
updateTorrentsView(true);
}
public void showDialog(int id) {
new DialogWrapper(onCreateDialog(id)).show(getSherlockActivity().getSupportFragmentManager(), DialogWrapper.TAG + id);
}
protected void dismissDialog(int id) {
// Remove the dialog wrapper fragment for the dialog's ID
getSherlockActivity().getSupportFragmentManager().beginTransaction().remove(
getSherlockActivity().getSupportFragmentManager().findFragmentByTag(DialogWrapper.TAG + id)).commit();
}
/**
* Returns the type of the currently active (shown) daemon
* @return The enum type of the active daemon
*/
public Daemon getActiveDaemonType() {
return daemon.getType();
}
/*@Override
public boolean onTouchEvent(MotionEvent me) {
return gestureDetector.onTouchEvent(me);
}*/
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
/**
* Internal class that handles gestures from the Transdroid main screen (a 'swipe' or 'fling').
*
* More at http://stackoverflow.com/questions/937313/android-basic-gesture-detection
*/
class MainScreenGestureListener extends SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onDoubleTap (MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1 != null && e2 != null) {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
return false;
}
if (daemon != null && interfaceSettings != null) {
if (Daemon.supportsLabels(daemon.getType()) && interfaceSettings.shouldSwipeLabels()) {
// Determine to which label to switch
String[] allLabels = buildLabelTexts(true);
int newLabel = 0;
if (activeLabel != null) {
for (int i = 0; i < allLabels.length; i++) {
if (activeLabel.equals(allLabels[i])) {
newLabel = i;
break;
}
}
}
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newLabel++;
if (newLabel >= allLabels.length) {
newLabel = 0;
}
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newLabel--;
if (newLabel < 0) {
newLabel = allLabels.length - 1;
}
}
// Make the switch, if possible and needed
if (newLabel >=0 && newLabel < allLabels.length && (activeLabel == null || activeLabel != allLabels[newLabel])) {
activeLabel = allLabels[newLabel];
updateTorrentsView(true);
}
} else {
// Determine to which daemon we are now switching
int newDaemon = lastUsedDaemonSettings;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newDaemon = lastUsedDaemonSettings + 1;
if (newDaemon >= allDaemonSettings.size()) {
newDaemon = 0;
}
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newDaemon = lastUsedDaemonSettings - 1;
if (newDaemon < 0) {
newDaemon = allDaemonSettings.size() - 1;
}
}
// Make the switch, if needed
if (lastUsedDaemonSettings != newDaemon) {
switchDaemonConfig(newDaemon);
}
}
}
}
return false;
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import java.util.List;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.Torrent;
import org.transdroid.gui.util.ArrayAdapter;
import android.view.View;
import android.view.ViewGroup;
/**
* An adapter that can be mapped to a list of torrents.
* @author erickok
*
*/
public class TorrentListAdapter extends ArrayAdapter<Torrent> {
TorrentsFragment mainScreen;
public TorrentListAdapter(TorrentsFragment mainScreen, List<Torrent> torrents) {
super(mainScreen.getActivity(), torrents);
this.mainScreen = mainScreen;
}
public View getView(int position, View convertView, ViewGroup paret) {
if (convertView == null) {
// Create a new view
return new TorrentListView(getContext(), getItem(position), Daemon.supportsAvailability(mainScreen.getActiveDaemonType()));
} else {
// Reuse view
TorrentListView setView = (TorrentListView) convertView;
setView.setData(getItem(position), Daemon.supportsAvailability(mainScreen.getActiveDaemonType()));
return setView;
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.ifies.android.sax.Item;
import org.ifies.android.sax.RssParser;
import org.transdroid.R;
import org.transdroid.gui.util.ArrayAdapter;
import org.transdroid.rss.RssFeedSettings;
import org.transdroid.util.TLog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
/**
* An adapter that can be mapped to a list of rss feeds.
* @author erickok
*
*/
public class RssFeedListAdapter extends ArrayAdapter<RssFeedSettings> {
private static final String LOG_NAME = "RSS feeds";
private List<String> unreadMessages;
public RssFeedListAdapter(Context context, List<RssFeedSettings> feeds) {
super(context, feeds);
// Maintain a list where, for each of the feeds, the number of unread messages is kept
// Initially this will show '?' (loading) and an asynchronous process will fill these
this.unreadMessages = new ArrayList<String>();
for (int i = 0; i < feeds.size(); i++) {
unreadMessages.add("?");
retrieveUnreadPostCount(i);
}
}
public View getView(int position, View convertView, ViewGroup paret) {
if (convertView == null) {
// Create a new view
return new RssFeedListView(getContext(), getItem(position), unreadMessages.get(position));
} else {
// Reuse view
RssFeedListView setView = (RssFeedListView) convertView;
setView.setData(getItem(position), unreadMessages.get(position));
return setView;
}
}
private void retrieveUnreadPostCount(final int position) {
final RssFeedSettings settings = getItem(position);
TLog.d(LOG_NAME, "Retreiving unread item count for RSS feed " + settings.getName());
final Handler retrieveHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Error?
if (msg.what == -1) {
// .obj contains the exception object
Toast.makeText(getContext(), settings.getName() + ": " + ((Exception)msg.obj).getMessage(), Toast.LENGTH_LONG).show();
unreadMessages.set(position, "?");
RssFeedListAdapter.this.notifyDataSetChanged();
return;
}
// Number of unread messages is on the message .obj and the settings object key as integer in .what
if (Integer.parseInt(settings.getKey()) == msg.what) {
unreadMessages.set(position, ((Integer)msg.obj).toString());
RssFeedListAdapter.this.notifyDataSetChanged();
}
}
};
// Asynchronous getting of the number of unread messages
new Thread() {
@Override
public void run() {
try {
// Load RSS items
RssParser parser = new RssParser(settings.getUrl());
parser.parse();
if (parser.getChannel() == null) {
throw new Exception(getContext().getResources().getString(R.string.error_norssfeed));
}
// Count items until that last known read item is found again
// Note that the item URL is used as unique identifier
int unread = 0;
List<Item> items = parser.getChannel().getItems();
Collections.sort(items, Collections.reverseOrder());
for (Item item : items) {
if (settings.getLastNew() == null || item == null || item.getTheLink() == null || item.getTheLink().equals(settings.getLastNew())) {
break;
}
unread++;
}
// Return the found number of unread messages
TLog.d(LOG_NAME, "RSS feed " + settings.getName() + " has " + unread + " new messages.");
Message msg = Message.obtain();
msg.what = Integer.parseInt(settings.getKey());
msg.obj = unread;
retrieveHandler.sendMessage(msg);
} catch (Exception e) {
// Return the error to the callback
TLog.d(LOG_NAME, e.toString());
Message msg = Message.obtain();
msg.what = -1;
msg.obj = e;
retrieveHandler.sendMessage(msg);
}
}
}.start();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import org.transdroid.R;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class RssFeeds extends SherlockFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rssfeeds);
getSupportActionBar().setDisplayShowTitleEnabled(true);
if (savedInstanceState == null) {
// Start the fragment
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.feeds, new RssFeedsFragment());
ft.commit();
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import java.util.List;
import org.transdroid.R;
import org.transdroid.gui.Transdroid;
import org.transdroid.preferences.Preferences;
import org.transdroid.preferences.PreferencesRss;
import org.transdroid.rss.RssFeedSettings;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class RssFeedsFragment extends SherlockFragment {
// private static final String LOG_NAME = "Transdroid RSS feeds";
private static final int ACTIVITY_PREFERENCES = 0;
private static final int MENU_REFRESH_ID = 1;
private static final int MENU_SETTINGS_ID = 2;
protected boolean useTabletInterface;
public RssFeedsFragment() {
setHasOptionsMenu(true);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_rssfeeds, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
useTabletInterface = Transdroid.isTablet(getResources());
registerForContextMenu(getView().findViewById(android.R.id.list));
getSherlockActivity().getSupportActionBar().setTitle(R.string.rss);
getListView().setOnItemClickListener(onFeedClicked);
getSherlockActivity().setTitle(R.string.rss);
loadFeeds();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Add title bar buttons
MenuItem miRefresh = menu.add(0, MENU_REFRESH_ID, 0, R.string.refresh);
miRefresh.setIcon(R.drawable.icon_refresh_title);
miRefresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
// Add the settings button
MenuItem miSettings = menu.add(0, MENU_SETTINGS_ID, 0,
R.string.menu_settings);
miSettings.setIcon(android.R.drawable.ic_menu_preferences);
}
private void loadFeeds() {
// Read the feed settings from the user preferences
// Note that the 'number of new items' is retrieved asynchronously from
// within the RssFeedListAdapter
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
List<RssFeedSettings> feeds = Preferences.readAllRssFeedSettings(prefs);
setListAdapter(new RssFeedListAdapter(getActivity(), feeds));
}
private OnItemClickListener onFeedClicked = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Show the feed items in the right of the screen (tablet interface) or separately
if (useTabletInterface) {
FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.listing, new RssListingFragment(getListAdapter().getItem(position)));
ft.commit();
} else {
// Open the listing for the clicked RSS feed
String postfix = getListAdapter().getItem(position).getKey();
Intent i = new Intent(getActivity(), RssListing.class);
i.putExtra(RssListing.RSSFEED_LISTING_KEY, postfix);
startActivity(i);
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH_ID:
loadFeeds();
break;
case MENU_SETTINGS_ID:
startActivityForResult(new Intent(getActivity(),
PreferencesRss.class), ACTIVITY_PREFERENCES);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ACTIVITY_PREFERENCES:
// Preference screen was called: use new preferences to show new
// feeds
loadFeeds();
break;
}
}
protected ListView getListView() {
return (ListView) getView().findViewById(android.R.id.list);
}
protected RssFeedListAdapter getListAdapter() {
return (RssFeedListAdapter) getListView().getAdapter();
}
private View getEmptyText() {
return getView().findViewById(android.R.id.empty);
}
private void setListAdapter(RssFeedListAdapter rssFeedListAdapter) {
getListView().setAdapter(rssFeedListAdapter);
if (rssFeedListAdapter == null || rssFeedListAdapter.getCount() <= 0) {
getListView().setVisibility(View.GONE);
getEmptyText().setVisibility(View.VISIBLE);
} else {
getListView().setVisibility(View.VISIBLE);
getEmptyText().setVisibility(View.GONE);
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.ifies.android.sax.Item;
import org.ifies.android.sax.RssParser;
import org.transdroid.R;
import org.transdroid.gui.Torrents;
import org.transdroid.gui.Transdroid;
import org.transdroid.gui.search.Search;
import org.transdroid.gui.util.DialogWrapper;
import org.transdroid.gui.util.SelectableArrayAdapter.OnSelectedChangedListener;
import org.transdroid.preferences.Preferences;
import org.transdroid.rss.RssFeedSettings;
import org.transdroid.util.TLog;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
@SuppressLint("ValidFragment")
public class RssListingFragment extends SherlockFragment implements OnTouchListener, OnSelectedChangedListener {
private static final String LOG_NAME = "RSS listing";
private static final int MENU_REFRESH_ID = 1;
private static final int ITEMMENU_ADD_ID = 10;
private static final int ITEMMENU_BROWSE_ID = 11;
private static final int ITEMMENU_DETAILS_ID = 12;
private static final int ITEMMENU_USEASSEARCH_ID = 13;
private static final int DIALOG_ITEMDETAILS = 20;
private TextView empty;
private LinearLayout addSelected;
private Button addSelectedButton;
private GestureDetector gestureDetector;
private boolean inProgress = false;
private List<RssFeedSettings> allFeeds = null;
protected List<Item> lastLoadedItems = null;
private RssFeedSettings feedSettings;
private boolean ignoreFirstListNavigation = true;
private String detailsDialogText;
public RssListingFragment(RssFeedSettings feedSettings) {
this.feedSettings = feedSettings;
setHasOptionsMenu(true);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_rsslisting, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(getListView());
getListView().setOnItemClickListener(onItemClicked);
empty = (TextView) getView().findViewById(android.R.id.empty);
addSelected = (LinearLayout) getView().findViewById(R.id.add_selected);
addSelectedButton = (Button) getView().findViewById(R.id.add_selectedbutton);
addSelectedButton.setOnClickListener(addSelectedClicked);
// Swiping or flinging between server configurations
gestureDetector = new GestureDetector(new RssScreenGestureListener());
getSherlockActivity().getSupportActionBar().setTitle(R.string.rss);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
allFeeds = Preferences.readAllRssFeedSettings(prefs);
ignoreFirstListNavigation = true;
if (getActivity() instanceof RssListing) {
getSherlockActivity().getSupportActionBar().setListNavigationCallbacks(buildFeedsAdapter(), onFeedSelected);
}
if (lastLoadedItems == null || feedSettings == null) {
// Start loading the items
loadItems();
} else {
// Set items from the retained instance state
if (getActivity() instanceof RssListing) {
getSherlockActivity().getSupportActionBar().setSelectedNavigationItem(feedSettingsIndex(feedSettings));
setListAdapter(new RssItemListAdapter(getActivity(), RssListingFragment.this, lastLoadedItems, true, feedSettings.getLastNew()));
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, ITEMMENU_ADD_ID, 0, R.string.searchmenu_add);
menu.add(0, ITEMMENU_BROWSE_ID, 0, R.string.searchmenu_details);
menu.add(0, ITEMMENU_DETAILS_ID, 0, R.string.details_details);
menu.add(0, ITEMMENU_USEASSEARCH_ID, 0, R.string.searchmenu_useassearch);
}
private void loadItems() {
setListAdapter(null);
if (feedSettings == null) {
empty.setText(R.string.rss_no_items);
return;
}
// Show the 'loading' icon (rotating indeterminate progress bar)
setProgressBar(true);
empty.setText(R.string.rss_loading_feed);
// Show the (newly) selected feed
if (getActivity() instanceof RssListing && feedSettings.getName() != null && !feedSettings.getName().equals("")) {
ignoreFirstListNavigation = true;
getSherlockActivity().getSupportActionBar().setSelectedNavigationItem(feedSettingsIndex(feedSettings));
}
// Read the RSS items asynchronously
final Handler retrieveHandler = new Handler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
// Not loading any more, turn off status indicator
setProgressBar(false);
// Error?
if (msg.what == -1) {
String errorMessage = ((Exception)msg.obj).getMessage();
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
empty.setText(errorMessage);
return;
}
// The list of items is contained in the message obj
List<Item> items = (List<Item>) msg.obj;
lastLoadedItems = items;
if (items == null || items.size() == 0) {
empty.setText(R.string.rss_no_items);
} else {
setListAdapter(new RssItemListAdapter(getActivity(), RssListingFragment.this, items, true, feedSettings.getLastNew()));
// Also store the 'last url' for the newest item that we now viewed
// (The most recent is always the first item, we assume)
Editor manager = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();
manager.putString(Preferences.KEY_PREF_RSSLASTNEW + feedSettings.getKey(), items.get(0).getTheLink());
manager.commit();
feedSettings.setLastNew(items.get(0).getTheLink());
}
}
};
// Asynchronous getting of the RSS items
new Thread() {
@Override
public void run() {
try {
// Load RSS items
RssParser parser = new RssParser(feedSettings.getUrl());
parser.parse();
if (parser.getChannel() == null) {
throw new Exception(getResources().getString(R.string.error_norssfeed));
}
List<Item> items = parser.getChannel().getItems();
Collections.sort(items, Collections.reverseOrder());
// Return the list of items
TLog.d(LOG_NAME, "RSS feed " + feedSettings.getName() + " has " + items.size() + " messages.");
Message msg = Message.obtain();
msg.what = 1;
msg.obj = items;
retrieveHandler.sendMessage(msg);
} catch (Exception e) {
// Return the error to the callback
TLog.d(LOG_NAME, e.toString());
Message msg = Message.obtain();
msg.what = -1;
msg.obj = e;
retrieveHandler.sendMessage(msg);
}
}
}.start();
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Item result = (Item) getListAdapter().getItem((int) info.id);
switch (item.getItemId()) {
case ITEMMENU_ADD_ID:
// Directly add this torrent
addTorrent(result);
break;
case ITEMMENU_BROWSE_ID:
// Open the browser to show the website contained in the item's link tag
if (result.getLink() != null && !result.getLink().equals("")) {
Uri uri = Uri.parse(result.getLink());
startActivity(new Intent(Intent.ACTION_VIEW, uri));
} else {
// No URL was specified in the RSS feed item link tag (or no link tag was present)
Toast.makeText(getActivity(), R.string.error_no_link, Toast.LENGTH_LONG).show();
}
break;
case ITEMMENU_DETAILS_ID:
// Show a dialog box with the RSS item description text
detailsDialogText = result.getDescription();
showDialog(DIALOG_ITEMDETAILS);
break;
case ITEMMENU_USEASSEARCH_ID:
// Use the title of this torrent as a new search query
Intent search = new Intent(getActivity(), Search.class);
search.setAction(Intent.ACTION_SEARCH);
search.putExtra(SearchManager.QUERY, result.getTitle());
startActivity(search);
break;
}
return true;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Add title bar buttons
if (getActivity() instanceof RssListing) {
MenuItem miRefresh = menu.add(0, MENU_REFRESH_ID, 0, R.string.refresh);
miRefresh.setIcon(R.drawable.icon_refresh_title);
miRefresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS|MenuItem.SHOW_AS_ACTION_WITH_TEXT);
if (inProgress ) {
// Show progress spinner instead of the option item
View view = getActivity().getLayoutInflater().inflate(R.layout.part_actionbar_progressitem, null);
miRefresh.setActionView(view);
}
}
}
private OnItemClickListener onItemClicked = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Item item = (Item) getListAdapter().getItem(position);
// If something was already selected before
if (!getRssItemListAdapter().getSelected().isEmpty()) {
getRssItemListAdapter().itemChecked(item, !getRssItemListAdapter().isItemChecked(item));
getListView().invalidateViews();
} else {
// No selection: add directly
addTorrent(item);
}
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH_ID:
loadItems();
break;
}
return super.onOptionsItemSelected(item);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ITEMDETAILS:
// Build a dialog with a description text
AlertDialog.Builder detailsDialog = new AlertDialog.Builder(getActivity());
detailsDialog.setTitle(R.string.details_details);
detailsDialog.setMessage(Html.fromHtml((detailsDialogText == null? "": detailsDialogText)));
detailsDialog.setNeutralButton(android.R.string.ok, null);
return detailsDialog.create();
/*case DIALOG_FEEDS:
// Build a dialog with a radio box per RSS feed
AlertDialog.Builder feedsDialog = new AlertDialog.Builder(this);
feedsDialog.setTitle(R.string.pref_rss_info);
feedsDialog.setSingleChoiceItems(
buildFeedTextsForDialog(), // The strings of the available RSS feeds
feedSettingsIndex(feedSettings),
new DialogInterface.OnClickListener() {
@Override
// When the feed is clicked (and it is different from the current shown feed),
// change the feed to show
public void onClick(DialogInterface dialog, int which) {
RssFeedSettings selected = allFeeds.get(which);
if (selected.getKey() != feedSettings.getKey()) {
feedSettings = selected;
loadItems();
}
removeDialog(DIALOG_FEEDS);
}
});
return feedsDialog.create();*/
}
return null;
}
/*@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_ITEMDETAILS:
AlertDialog detailsDialog = (AlertDialog) dialog;
detailsDialog.setMessage(Html.fromHtml(detailsDialogText == null? "": detailsDialogText));
break;
}
super.onPrepareDialog(id, dialog);
}*/
private int feedSettingsIndex(RssFeedSettings afeed) {
int i = 0;
for (RssFeedSettings feed : allFeeds) {
if (feed.getKey().equals(afeed.getKey())) {
return i;
}
i++;
}
return -1;
}
private SpinnerAdapter buildFeedsAdapter() {
ArrayAdapter<String> ad = new ArrayAdapter<String>(getActivity(), R.layout.abs__simple_spinner_item, buildFeedTextsForDialog());
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return ad;
}
private String[] buildFeedTextsForDialog() {
// Build a textual list of RSS feeds available
ArrayList<String> feeds = new ArrayList<String>();
for (RssFeedSettings feed : allFeeds) {
feeds.add(feed.getName());
}
return feeds.toArray(new String[feeds.size()]);
}
private OnNavigationListener onFeedSelected = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int which, long itemId) {
if (!ignoreFirstListNavigation) {
RssFeedSettings selected = allFeeds.get(which);
if (selected.getKey() != feedSettings.getKey()) {
feedSettings = selected;
loadItems();
}
}
ignoreFirstListNavigation = false;
return true;
}
};
private RssItemListAdapter getRssItemListAdapter() {
return (RssItemListAdapter) getListAdapter();
}
private void addTorrent(Item item) {
// The actual torrent URL is usually contained an 'enclosure' or the link tag
if (item.getTheLink() != null && !item.getTheLink().equals("")) {
Intent i;
if (feedSettings.needsAuthentication()) {
// Redirect links to the Android browser instead of directly adding it via URL
i = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getTheLink()));
} else {
// Build new intent that Transdroid can pick up again
i = new Intent(getActivity(), Torrents.class);
i.setData(Uri.parse(item.getTheLink()));
}
// Create a result for the calling activity
//setResult(RESULT_OK);
startActivity(i);
getSherlockActivity().getSupportFragmentManager().popBackStack();
} else {
// No URL was specified in the RSS feed item
Toast.makeText(getActivity(), R.string.error_no_url_enclosure, Toast.LENGTH_LONG).show();
}
}
private void addTorrents(List<Item> items) {
// The actual torrent URL is usually contained an 'enclosure' or the link tag
// We will test the first selected item, since it is very likely that if this has a link, the others will as well
if (items != null && items.size() > 0) {
if (items.get(0).getTheLink() != null && !items.get(0).getTheLink().equals("")) {
// Build new intent that Transdroid can pick up again
// This sets the data to "<url>|<url>|..."
Intent i = new Intent(getActivity(), Torrents.class);
String[] urls = new String[items.size()];
for (int j = 0; j < items.size(); j++) {
urls[j] = items.get(j).getTheLink();
}
i.setAction(Transdroid.INTENT_ADD_MULTIPLE);
i.putExtra(Transdroid.INTENT_TORRENT_URLS, urls);
// Create a result for the calling activity
//setResult(RESULT_OK);
startActivity(i);
getSherlockActivity().getSupportFragmentManager().popBackStack();
} else {
// No URL was specified in the RSS feed item
Toast.makeText(getActivity(), R.string.error_no_url_enclosure, Toast.LENGTH_LONG).show();
}
}
}
private void setProgressBar(boolean b) {
inProgress = b;
if (getSherlockActivity() != null) {
getSherlockActivity().supportInvalidateOptionsMenu();
}
}
/*@Override
public boolean onTouchEvent(MotionEvent me) {
return gestureDetector.onTouchEvent(me);
}*/
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
/**
* Internal class that handles gestures from the search screen (a 'swipe' or 'fling').
*
* More at http://stackoverflow.com/questions/937313/android-basic-gesture-detection
*/
class RssScreenGestureListener extends SimpleOnGestureListener {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onDoubleTap (MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1 != null && e2 != null) {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
return false;
}
// Determine to which feed we are now switching
int newFeed = feedSettingsIndex(feedSettings);
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newFeed += 1;
if (newFeed >= allFeeds.size()) {
newFeed = 0;
}
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
newFeed -= 1;
if (newFeed < 0) {
newFeed = allFeeds.size() - 1;
}
}
// Make the switch, if needed
RssFeedSettings newFeedSettings = allFeeds.get(newFeed);
if (!newFeedSettings.getKey().equals(feedSettings.getKey())) {
feedSettings = newFeedSettings;
loadItems();
}
}
return false;
}
}
/**
* Called by the SelectableArrayAdapter when the set of selected items changed
*/
public void onSelectedResultsChanged() {
RssItemListAdapter adapter = (RssItemListAdapter) getListAdapter();
if (adapter.getSelected().size() == 0) {
// Hide the 'add selected' button
addSelected.setVisibility(View.GONE);
} else {
addSelected.setVisibility(View.VISIBLE);
}
}
private OnClickListener addSelectedClicked = new OnClickListener() {
@Override
public void onClick(View v) {
// Send the urls of all selected search result back to Transdroid
RssItemListAdapter adapter = (RssItemListAdapter) getListAdapter();
addTorrents(adapter.getSelected());
}
};
public void showDialog(int id) {
new DialogWrapper(onCreateDialog(id)).show(getSherlockActivity().getSupportFragmentManager(), DialogWrapper.TAG + id);
}
protected void dismissDialog(int id) {
// Remove the dialog wrapper fragment for the dialog's ID
getSherlockActivity().getSupportFragmentManager().beginTransaction().remove(
getSherlockActivity().getSupportFragmentManager().findFragmentByTag(DialogWrapper.TAG + id)).commit();
}
protected ListView getListView() {
return (ListView) getView().findViewById(android.R.id.list);
}
protected RssItemListAdapter getListAdapter() {
return (RssItemListAdapter) getListView().getAdapter();
}
private View getEmptyText() {
return getView().findViewById(android.R.id.empty);
}
private void setListAdapter(RssItemListAdapter adapter) {
getListView().setAdapter(adapter);
if (adapter == null || adapter.getCount() <= 0) {
getListView().setVisibility(View.GONE);
getEmptyText().setVisibility(View.VISIBLE);
} else {
getListView().setVisibility(View.VISIBLE);
getEmptyText().setVisibility(View.GONE);
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import org.transdroid.R;
import org.transdroid.preferences.Preferences;
import org.transdroid.rss.RssFeedSettings;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class RssListing extends SherlockFragmentActivity {
public static final String RSSFEED_LISTING_KEY = "RSSFEED_LISTING_KEY";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rsslisting);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
if (savedInstanceState == null) {
// Get the ID of the RSS feed to load
String postfix = getIntent().getStringExtra(RSSFEED_LISTING_KEY);
// Get settings form user preferences
RssFeedSettings feedSettings = Preferences.readRssFeedSettings(PreferenceManager.getDefaultSharedPreferences(this), postfix);
// Start the fragment for this torrent
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.items, new RssListingFragment(feedSettings));
ft.commit();
}
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import java.util.ArrayList;
import java.util.List;
import org.ifies.android.sax.Item;
import org.transdroid.gui.util.SelectableArrayAdapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
/**
* An adapter that can be mapped to a list of rss items.
* @author erickok
*
*/
public class RssItemListAdapter extends SelectableArrayAdapter<Item> {
private List<Boolean> isNew;
private boolean enableCheckboxes;
public RssItemListAdapter(Context context, OnSelectedChangedListener listener, List<Item> items, boolean enableCheckboxes, String lastNew) {
super(context, items, listener);
this.enableCheckboxes = enableCheckboxes;
// The 'last new' item url used to see which items are new since the last viewing of this feed
// For each item in the items list, there is one boolean in the isNew list indicating if it is new
boolean stillNew = true;
isNew = new ArrayList<Boolean>();
for (Item item : items) {
if (lastNew == null || item.getTheLink() == null || item.getTheLink().equals(lastNew)) {
stillNew = false;
}
isNew.add(new Boolean(stillNew));
}
}
@Override
public View getView(int position, View convertView, ViewGroup paret, boolean selected) {
// TODO: Try to reuse the view to improve scrolling performance
return new RssItemListView(getContext(), this, getItem(position), isNew.get(position), enableCheckboxes, selected);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import org.transdroid.R;
import org.transdroid.rss.RssFeedSettings;
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* A view that shows an rss feed and its number of unread items as a list view.
*
* The number of unread items is received asynchronously.
*
* @author erickok
*
*/
public class RssFeedListView extends LinearLayout {
//private static final String LOG_NAME = "Transdroid RSS feeds";
/**
* Constructs a view that can display an rss feed name and number of new items since last time (to use in a list)
* @param context The activity context
* @param feedSettings The rss feed to show the data for
* @param unreadMessages The string showing the number of unread messages (or ? when it is still loading)
*/
public RssFeedListView(Context context, RssFeedSettings feedSettings, String unreadMessages) {
super(context);
addView(inflate(context, R.layout.list_item_rssfeed, null));
setData(feedSettings, unreadMessages);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void setData(RssFeedSettings feedSettings, String unreadMessages) {
TextView name = (TextView)findViewById(R.id.feed_name);
TextView count = (TextView)findViewById(R.id.feed_unreadcount);
ProgressBar loading = (ProgressBar)findViewById(R.id.feed_loading);
name.setText(feedSettings.getName());
if (unreadMessages.equals("?")) {
loading.setVisibility(VISIBLE);
count.setVisibility(GONE);
} else {
loading.setVisibility(GONE);
count.setText(unreadMessages);
count.setVisibility(VISIBLE);
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui.rss;
import java.util.Date;
import org.ifies.android.sax.Item;
import org.transdroid.R;
import android.content.Context;
import android.text.format.DateUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
/**
* A view that shows an RSS item (which is a link to some torrent) in a list view
*
* @author erickok
*
*/
public class RssItemListView extends LinearLayout {
private RssItemListAdapter adapter;
private Item item;
/**
* Constructs a view that can display RSS item data (to use in a list)
* @param context The activity context
* @param isNew Whether this message was new since the last viewin of the RSS feed
* @param torrent The RSS item to show the data for
*/
public RssItemListView(Context context, RssItemListAdapter adapter, Item item, boolean isNew, boolean isCheckable, boolean initiallyChecked) {
super(context);
this.adapter = adapter;
addView(inflate(context, R.layout.list_item_rssitem, null));
setData(item, isNew,isCheckable, initiallyChecked);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void setData(Item item, boolean isNew, boolean isCheckable, boolean initiallyChecked) {
this.item = item;
// Set the checkbox that allow picking of multiple results at once
final CheckBox check = (CheckBox)findViewById(R.id.rssitem_check);
if (isCheckable) {
check.setVisibility(VISIBLE);
check.setChecked(initiallyChecked);
check.setOnCheckedChangeListener(itemSelection);
} else {
check.setVisibility(GONE);
}
// Bind the data values to the text views
ImageView icon = ((ImageView)findViewById(R.id.rssitem_new));
TextView title = ((TextView)findViewById(R.id.rssitem_title));
TextView date = ((TextView)findViewById(R.id.rssitem_date));
icon.setImageResource(isNew? R.drawable.icon_new: R.drawable.icon_notnew);
title.setText(item.getTitle());
if (item.getPubdate() != null) {
date.setText(DateUtils.formatSameDayTime(item.getPubdate().getTime(), new Date().getTime(), java.text.DateFormat.MEDIUM, java.text.DateFormat.SHORT));
date.setVisibility(VISIBLE);
} else {
date.setText("");
date.setVisibility(GONE);
}
}
private OnCheckedChangeListener itemSelection = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
adapter.itemChecked(item, isChecked);
}
};
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.gui;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
/**
* The application's constants.
*
* @author erickok
*
*/
public class Transdroid {
public final static String SCAN_INTENT = "com.google.zxing.client.android.SCAN";
public static final Uri SCANNER_MARKET_URI = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
public static final String SCAN_FORMAT_QRCODE = "QR_CODE";
public static final String BITTORRENT_MIME = "application/x-bittorrent";
public static final String INTENT_OPENDAEMON = "org.transdroid.OPEN_DAEMON";
public static final String INTENT_ADD_MULTIPLE = "org.transdroid.ADD_MULTIPLE";
public static final String INTENT_TORRENT_URLS = "TORRENT_URLS";
public static final String INTENT_TORRENT_TITLES = "TORRENT_TITLES";
public static final String INTENT_TORRENT_TITLE = "TORRENT_TITLE";
public static final String REMOTEINTENT = "org.openintents.remote.intent.action.VIEW";
public static final String REMOTEINTENT_HOST = "org.openintents.remote.intent.extra.HOST";
public final static Uri VLCREMOTE_MARKET_URI = Uri.parse("market://search?q=pname:org.peterbaldwin.client.android.vlcremote");
public final static Uri ANDFTP_MARKET_URI = Uri.parse("market://search?q=pname:lysesoft.andftp");
public final static String ANDFTP_INTENT_TYPE = "vnd.android.cursor.dir/lysesoft.andftp.uri";
public final static String ANDFTP_INTENT_USER = "ftp_username";
public final static String ANDFTP_INTENT_PASS = "ftp_password";
public final static String ANDFTP_INTENT_PASV = "ftp_pasv";
public final static String ANDFTP_INTENT_CMD = "command_type";
public final static String ANDFTP_INTENT_FILE = "remote_file1";
public final static String ANDFTP_INTENT_LOCAL = "local_folder";
/**
* Returns whether the device is a tablet (or better: whether it can fit a tablet layout)
* @param r The application resources
* @return True if the device is a tablet, false otherwise
*/
public static boolean isTablet(Resources r) {
//boolean hasLargeScreen = ((r.getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
boolean hasXLargeScreen = ((r.getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) &&
android.os.Build.VERSION.SDK_INT >= 11;
return hasXLargeScreen;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, UpdateService.class));
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, AlarmService.class));
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.service;
/**
* The settings for the Alarm service
*
* @author erickok
*/
public class AlarmSettings{
private boolean enableAlarm;
private int alarmInterval;
private boolean checkRssFeeds;
private boolean alarmPlaySound;
private String alarmSoundURI;
private boolean alarmVibrate;
private int alarmColour;
private boolean adwNotify;
private boolean adwOnlyDl;
private boolean checkForUpdates;
public AlarmSettings(boolean enableAlarm, int alarmInterval, boolean checkRssFeeds, boolean alarmPlaySound, String alarmSoundURI, boolean alarmVibrate, int alarmColour, boolean adwNotify, boolean adwOnlyDl, boolean checkForUpdates) {
this.enableAlarm = enableAlarm;
this.alarmInterval = alarmInterval;
this.checkRssFeeds = checkRssFeeds;
this.alarmPlaySound = alarmPlaySound;
this.alarmSoundURI = alarmSoundURI;
this.alarmVibrate = alarmVibrate;
this.alarmColour = alarmColour;
this.adwNotify = adwNotify;
this.adwOnlyDl = adwOnlyDl;
this.checkForUpdates = checkForUpdates;
}
public boolean isAlarmEnabled() {
return enableAlarm;
}
public int getAlarmIntervalInSeconds() {
return alarmInterval;
}
public long getAlarmIntervalInMilliseconds() {
return getAlarmIntervalInSeconds() * 1000;
}
public boolean shouldCheckRssFeeds() {
return checkRssFeeds;
}
public boolean getAlarmPlaySound() {
return alarmPlaySound;
}
public String getAlarmSoundURI() {
return alarmSoundURI;
}
public boolean getAlarmVibrate() {
return alarmVibrate;
}
public int getAlarmColour() {
return alarmColour;
}
public boolean showAdwNotifications() {
return adwNotify;
}
public boolean showOnlyDownloadsInAdw() {
return adwOnlyDl;
}
public boolean shouldCheckForUpdates() {
return checkForUpdates;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.service;
import org.transdroid.preferences.Preferences;
import org.transdroid.util.TLog;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.preference.PreferenceManager;
/**
* Receives a broadcast message when the device has started and is used to manually start/stop the alarm
* service.
*
* @author erickok
*
*/
public class BootReceiver extends BroadcastReceiver {
private static final String LOG_NAME = "Boot receiver";
private static AlarmManager mgr = null;
private static PendingIntent pi = null;
private static PendingIntent pui = null;
@Override
public void onReceive(Context context, Intent intent) {
TLog.d(LOG_NAME, "Received fresh boot broadcast; start alarm service");
startAlarm(context);
startUpdateCheck(context);
}
public static void cancelAlarm() {
if (mgr != null) {
mgr.cancel(pi);
}
}
public static void startAlarm(Context context) {
AlarmSettings settings = Preferences.readAlarmSettings(PreferenceManager.getDefaultSharedPreferences(context));
if (settings.isAlarmEnabled()) {
// Set up PendingIntent for the alarm service
if (mgr == null)
mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
pi = PendingIntent.getBroadcast(context, 0, i, 0);
// First intent after a small (2 second) delay and repeat at the user-set intervals
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, settings
.getAlarmIntervalInMilliseconds(), pi);
}
}
public static void cancelUpdateCheck() {
if (mgr != null) {
mgr.cancel(pui);
}
}
public static void startUpdateCheck(Context context) {
// Set up PendingIntent for the alarm service
if (mgr == null)
mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, UpdateReceiver.class);
pui = PendingIntent.getBroadcast(context, 1, i, 0);
// First intent after a small (2 second) delay and repeat every day
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000,
AlarmManager.INTERVAL_DAY, pui);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ifies.android.sax.Item;
import org.ifies.android.sax.RssParser;
import org.transdroid.R;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.Pair;
import org.transdroid.gui.Torrents;
import org.transdroid.gui.Transdroid;
import org.transdroid.gui.rss.RssFeeds;
import org.transdroid.preferences.Preferences;
import org.transdroid.rss.RssFeedSettings;
import org.transdroid.util.TLog;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.preference.PreferenceManager;
/**
* A service that regularly checks (on alarm intents) for newly finished downloads, etc.
*
* @author erickok
*
*/
public class AlarmService extends IntentService {
public static final String INTENT_FORCE_CHECK = "org.transdroid.service.FORCE_CHECK";
private static final String LOG_NAME = "Alarm service";
private static final int MAX_NOTIFICATIONS = 5;
private static final int RSS_NOTIFICATION = MAX_NOTIFICATIONS + 1; // Only use a single (overriding) notification for RSS-related messages
private static int notificationCounter = 0;
private static NotificationManager notificationManager;
public AlarmService() {
super(LOG_NAME);
// Attach the Android TLog to the daemon logger
DLog.setLogger(TLog.getInstance());
}
@Override
protected void onHandleIntent(Intent intent) {
// Settings
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
AlarmSettings settings = Preferences.readAlarmSettings(prefs);
List<DaemonSettings> daemonSettings = Preferences.readAllDaemonSettings(prefs);
DaemonSettings lastUsedDaemon = Preferences.readLastUsedDaemonSettings(prefs, daemonSettings);
boolean onlyShowTransferring = prefs.getBoolean(Preferences.KEY_PREF_LASTSORTGTZERO, false);
// How was the service called?
boolean forcedStarted = intent != null && intent.getAction() != null && intent.getAction().equals(INTENT_FORCE_CHECK);
// If not forcefully started, check if the user has background data disabled
if (!forcedStarted) {
ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (!conn.getBackgroundDataSetting()) {
TLog.d(LOG_NAME, "Skip any alarm service activity, since background data is deisabled on a system-wide level");
return;
}
}
// Add any torrents that were queued earlier when adding them failed
List<Pair<String, String>> queue = Preferences.readAndClearTorrentAddQueue(prefs);
if (queue != null && queue.size() > 0) {
String failedAgain = "";
for (Pair<String, String> torrent : queue) {
// Find the daemon where this queued torrent needs to be added to
for (DaemonSettings daemonSetting : daemonSettings) {
if (daemonSetting.getIdString().equals(torrent.first)) {
DaemonTaskResult result;
TLog.d(LOG_NAME, "Trying to add queued torrent '" + torrent.second + "' to " + daemonSetting.getHumanReadableIdentifier());
if (Preferences.isQueuedTorrentToAddALocalFile(torrent.second)) {
// Add this local .torrent file
result = AddByFileTask.create(daemonSetting.getType().createAdapter(daemonSetting), torrent.second).execute();
} else if (Preferences.isQueuedTorrentToAddAMagnetUrl(torrent.second)) {
// Add this magnet link by URL
result = AddByMagnetUrlTask.create(daemonSetting.getType().createAdapter(daemonSetting), torrent.second).execute();
} else {
// Add this web URL to a .torrent file
result = AddByUrlTask.create(daemonSetting.getType().createAdapter(daemonSetting), torrent.second, "Queued torrent").execute();
}
// If this failed again, remember it
// TODO: Max try, say, 5 times before finally removing it indefinitely
if (result instanceof DaemonTaskFailureResult) {
if (!failedAgain.equals("")) {
failedAgain += "|";
}
failedAgain += torrent.first + ";" + torrent.second;
}
break;
}
}
}
// Re-add any failed torrents to the queue again (ignoring those bound to non-existing daemons)
Preferences.addToTorrentAddQueue(prefs, failedAgain);
}
TLog.d(LOG_NAME, "Look at the servers for new torrents and started/finished downloads");
// For each daemon where alarms are enabled...
if (forcedStarted || settings.isAlarmEnabled()) {
Map<String, ArrayList<Pair<String, Boolean>>> lastUpdate = Preferences.readLastAlarmStatsUpdate(prefs);
HashMap<String, ArrayList<Pair<String, Boolean>>> thisUpdate = new HashMap<String, ArrayList<Pair<String, Boolean>>>();
for (DaemonSettings daemonSetting : daemonSettings) {
if (daemonSetting.getType() != null && (daemonSetting.shouldAlarmOnFinishedDownload() || daemonSetting.shouldAlarmOnNewTorrent())) {
// Synchronously get the torrent listing
TLog.d(LOG_NAME, daemonSetting.getHumanReadableIdentifier() + ": Retrieving torrent listing");
ArrayList<Pair<String, Boolean>> lastStat = null;
if (lastUpdate != null) {
lastStat = lastUpdate.get(daemonSetting.getIdString());
}
IDaemonAdapter daemon = daemonSetting.getType().createAdapter(daemonSetting);
if (daemon == null || daemon.getType() == null || daemon.getSettings() == null || daemon.getSettings().getAddress() == null) {
// Invalid settings
continue;
}
DaemonTaskResult result = RetrieveTask.create(daemon).execute();
if (!(result instanceof RetrieveTaskSuccessResult)) {
// If the task wasn't successful, go to the next daemon
if (lastStat != null) {
// Put back the old stats we knew about
thisUpdate.put(daemonSetting.getIdString(), lastStat);
}
continue;
}
// With the list of torrents...
List<Torrent> torrents = ((RetrieveTaskSuccessResult)result).getTorrents();
TLog.d(LOG_NAME, daemonSetting.getHumanReadableIdentifier() + ": " + torrents.size() + " torrents in this update");
if (lastUpdate == null) {
TLog.d(LOG_NAME, daemonSetting.getHumanReadableIdentifier() + ": " + "No last update found");
} else {
// And the list of torretn in the previous server update...
if (lastStat == null) {
TLog.d(LOG_NAME, daemonSetting.getHumanReadableIdentifier() + ": " + "Nothing known about it in the last update");
} else {
TLog.d(LOG_NAME, daemonSetting.getHumanReadableIdentifier() + ": " + lastStat.size() + " torrents in last update");
for (Torrent torrent : torrents) {
Pair<String, Boolean> torStat = findInLastUpdate(lastStat, torrent);
// Check for new torrents
if (daemonSetting.shouldAlarmOnNewTorrent()) {
if (torStat == null) {
// New torrent: add to notification
newNotification(null, getText(R.string.service_newtorrent).toString(), torrent.getName(), daemonSetting.getIdString(), Torrents.class);
}
}
// Check if a download finished
if (daemonSetting.shouldAlarmOnFinishedDownload()) {
if ((torStat != null && torStat.second.equals(Boolean.FALSE) && torrent.getPartDone() == 1f) ||
(torStat == null && torrent.getPartDone() == 1f)) {
// Finished (and it wasn't before): add notification
newNotification(null, getText(R.string.service_torrentfinished).toString(), torrent.getName(), daemonSetting.getIdString(), Torrents.class);
}
}
}
}
}
// For the last used server (by the user)...
if (settings.showAdwNotifications() && lastUsedDaemon.getIdString().equals(daemonSetting.getIdString())) {
// Count the number of (downloading) torrents
int count = 0;
for (Torrent torrent : torrents) {
if ((!settings.showOnlyDownloadsInAdw() || torrent.getStatusCode() == TorrentStatus.Downloading) &&
(!onlyShowTransferring || torrent.getRateDownload() > 0)) {
count++;
}
}
// Update ADW notification/counter
TLog.d(LOG_NAME, "Update ADW counter to " + count);
Intent iADWL = new Intent();
iADWL.setAction("org.adw.launcher.counter.SEND");
iADWL.putExtra("PNAME", getPackageName());
iADWL.putExtra("COUNT", count);
sendBroadcast(iADWL);
}
// Store the stats for this daemon
ArrayList<Pair<String, Boolean>> torStats = new ArrayList<Pair<String, Boolean>>();
for (Torrent torrent : torrents) {
torStats.add(new Pair<String, Boolean>(torrent.getUniqueID(), torrent.getPartDone() == 1f));
}
thisUpdate.put(daemonSetting.getIdString(), torStats);
}
}
// Store this stats update to compare to next time
Preferences.storeLastAlarmStatsUpdate(prefs, thisUpdate);
// Check for new RSS feed items
if (settings.shouldCheckRssFeeds()) {
List<RssFeedSettings> feeds = Preferences.readAllRssFeedSettings(prefs);
int unread = 0;
for (RssFeedSettings feed : feeds) {
try {
// Load RSS items
RssParser parser = new RssParser(feed.getUrl());
parser.parse();
if (parser.getChannel() != null) {
// Count items until that last known read item is found again
// Note that the item URL is used as unique identifier
List<Item> items = parser.getChannel().getItems();
Collections.sort(items, Collections.reverseOrder());
for (Item item : items) {
if (feed.getLastNew() == null || item == null || item.getTheLink() == null || item.getTheLink().equals(feed.getLastNew())) {
break;
}
unread++;
}
}
} catch (Exception e) {
// Ignore RSS items that could not be retrieved or parsed
}
}
if (unread > 0) {
newNotification(null, getString(R.string.service_newrssitems).toString(), getString(R.string.service_newrssitems_count, unread), null, RssFeeds.class);
}
}
}
}
private void newNotification(String ticker, String title, String text, String daemonConfigID, Class<?> intentStart) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
AlarmSettings settings = Preferences.readAlarmSettings(prefs);
// Set up an intent that will start Transdroid (and optionally change it to a specific daemon config)
Intent i = new Intent(AlarmService.this, intentStart);
if (daemonConfigID != null) {
i.putExtra(Transdroid.INTENT_OPENDAEMON, daemonConfigID);
}
// Create a new notification
int notifyID = notificationCounter;
if (intentStart.equals(RssFeeds.class)) {
notifyID = RSS_NOTIFICATION;
}
Notification newNotification = new Notification(R.drawable.icon_notification, ticker, System.currentTimeMillis());
newNotification.flags = Notification.FLAG_AUTO_CANCEL;
newNotification.setLatestEventInfo(getApplicationContext(), title, text,
PendingIntent.getActivity(getApplicationContext(), notifyID, i, 0));
// Get the system notification manager, if not done so previously
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
// If sound enabled add to notification
if (settings.getAlarmPlaySound() && settings.getAlarmSoundURI() != null) {
newNotification.sound = Uri.parse(settings.getAlarmSoundURI());
}
// If vibration enabled add to notification
if (settings.getAlarmVibrate()) {
newNotification.defaults = Notification.DEFAULT_VIBRATE;
}
// Add coloured light; defaults to 0xff7dbb21
newNotification.ledARGB = settings.getAlarmColour();
newNotification.ledOnMS = 600;
newNotification.ledOffMS = 1000;
newNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
// Send notification
notificationManager.notify(notifyID, newNotification);
// Never more than MAX_NOTIFICATIONS notifications active at one time
notificationCounter++;
notificationCounter = notificationCounter % MAX_NOTIFICATIONS;
}
private static Pair<String, Boolean> findInLastUpdate(ArrayList<Pair<String, Boolean>> lastStat, Torrent torrent) {
if (lastStat != null) {
for (Pair<String, Boolean> stat : lastStat) {
if (stat.first.equals(torrent.getUniqueID())) {
return stat;
}
}
}
return null;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.service;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.transdroid.R;
import org.transdroid.daemon.util.HttpHelper;
import org.transdroid.preferences.Preferences;
import org.transdroid.util.TLog;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.preference.PreferenceManager;
/**
* A service that checks if a new version of the app or the search module is available.
*
* @author erickok
*/
public class UpdateService extends IntentService {
private static final String LATEST_URL_APP = "http://www.transdroid.org/update/latest-app.php";
private static final String LATEST_URL_SEARCH = "http://www.transdroid.org/update/latest-search.php";
private static final String PACKAGE_APP = "org.transdroid";
private static final String PACKAGE_SEARCH = "org.transdroid.search";
private static final String DOWNLOAD_URL_APP = "http://www.transdroid.org/latest";
private static final String DOWNLOAD_URL_SEARCH = "http://www.transdroid.org/latest-search";
private static final String LOG_NAME = "Update service";
private static NotificationManager notificationManager;
private Random random = new Random();
public UpdateService() {
super(LOG_NAME);
}
@Override
protected void onHandleIntent(Intent intent) {
// Check if the user has background data disabled
ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (!conn.getBackgroundDataSetting()) {
TLog.d(LOG_NAME,
"Skip checking for new app versions, since background data is disabled on a system-wide level");
return;
}
// Check if the update service should run
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
AlarmSettings settings = Preferences.readAlarmSettings(prefs);
if (!settings.shouldCheckForUpdates()) {
TLog.d(LOG_NAME, "The user disabled the update checker service.");
return;
}
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
// Retrieve what is the latest released app and search module versions
String[] app = retrieveLatestVersion(httpclient, LATEST_URL_APP);
String[] search = retrieveLatestVersion(httpclient, LATEST_URL_SEARCH);
int appVersion = Integer.parseInt(app[0].trim());
int searchVersion = Integer.parseInt(search[0].trim());
// New version of the app?
try {
PackageInfo appPackage = getPackageManager().getPackageInfo(PACKAGE_APP, 0);
if (appPackage.versionCode < appVersion) {
// New version available! Notify the user.
newNotification(getString(R.string.update_app_newversion),
getString(R.string.update_app_newversion), getString(R.string.update_updateto,
app[1].trim()), DOWNLOAD_URL_APP + "?" + Integer.toString(random.nextInt()), 0);
}
} catch (NameNotFoundException e) {
// Not installed... this can never happen since this Service is part of the app itself.
}
// New version of the search module?
try {
PackageInfo searchPackage = getPackageManager().getPackageInfo(PACKAGE_SEARCH, 0);
if (searchPackage.versionCode < searchVersion) {
// New version available! Notify the user.
newNotification(getString(R.string.update_search_newversion),
getString(R.string.update_search_newversion), getString(R.string.update_updateto,
search[1].trim()), DOWNLOAD_URL_SEARCH + "?" + Integer.toString(random.nextInt()), 0);
}
} catch (NameNotFoundException e) {
// The search module isn't installed yet at all; ignore and wait for the user to manually
// install it (when the first search is initiated)
}
} catch (Exception e) {
// Cannot check right now for some reason; log and `ignore
TLog.d(LOG_NAME, "Cannot retrieve latest app or search module version code from the site: " + e.toString());
}
}
private String[] retrieveLatestVersion(AbstractHttpClient httpclient, String url) throws ClientProtocolException, IOException {
// Retrieve what is the latest released app version
HttpResponse request = httpclient.execute(new HttpGet(url));
InputStream stream = request.getEntity().getContent();
String appVersion[] = HttpHelper.ConvertStreamToString(stream).split("\\|");
stream.close();
return appVersion;
}
private void newNotification(String ticker, String title, String text, String downloadUrl, int notifyID) {
// Use the alarm service settings for the notification sound/vibrate/colour
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
AlarmSettings settings = Preferences.readAlarmSettings(prefs);
// Set up an intent that will initiate a download of the new version
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl));
// Create a new notification
Notification newNotification = new Notification(R.drawable.icon_notification, ticker, System
.currentTimeMillis());
newNotification.flags = Notification.FLAG_AUTO_CANCEL;
newNotification.setLatestEventInfo(getApplicationContext(), title, text, PendingIntent.getActivity(
getApplicationContext(), notifyID, i, 0));
// Get the system notification manager, if not done so previously
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
// If sound enabled add to notification
if (settings.getAlarmPlaySound() && settings.getAlarmSoundURI() != null) {
newNotification.sound = Uri.parse(settings.getAlarmSoundURI());
}
// If vibration enabled add to notification
if (settings.getAlarmVibrate()) {
newNotification.defaults = Notification.DEFAULT_VIBRATE;
}
// Add coloured light; defaults to 0xff7dbb21
newNotification.ledARGB = settings.getAlarmColour();
newNotification.ledOnMS = 600;
newNotification.ledOffMS = 1000;
newNotification.flags |= Notification.FLAG_SHOW_LIGHTS;
// Send notification
notificationManager.notify(notifyID, newNotification);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.service;
import java.util.List;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.PauseAllTask;
import org.transdroid.daemon.task.ResumeAllTask;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.task.StartAllTask;
import org.transdroid.daemon.task.StopAllTask;
import org.transdroid.daemon.util.DLog;
import org.transdroid.preferences.Preferences;
import org.transdroid.util.TLog;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
/**
* A service that can be asked to perform some control action on a
* remote torrent server via an Intent.
*
* @author erickok
*/
public class ControlService extends IntentService {
private static final String LOG_NAME = "Control service";
public static final String INTENT_SET_TRANSFER_RATES = "org.transdroid.control.SET_TRANSFER_RATES";
public static final String INTENT_PAUSE_ALL = "org.transdroid.control.PAUSE_ALL";
public static final String INTENT_RESUME_ALL = "org.transdroid.control.RESUME_ALL";
public static final String INTENT_START_ALL = "org.transdroid.control.START_ALL";
public static final String INTENT_STOP_ALL = "org.transdroid.control.STOP_ALL";
public static final String INTENT_EXTRA_DAEMON = "DAEMON";
public static final String INTENT_EXTRA_UPLOAD_RATE = "UPLOAD_RATE";
public static final String INTENT_EXTRA_DOWNLOAD_RATE = "DOWNLOAD_RATE";
public ControlService() {
super(LOG_NAME);
// Attach the Android TLog to the daemon logger
DLog.setLogger(TLog.getInstance());
}
@Override
protected void onHandleIntent(Intent intent) {
// Settings
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
List<DaemonSettings> allSettings = Preferences.readAllDaemonSettings(prefs);
// Get the daemon to execute the action against
DaemonSettings daemonSetting = parseDaemonFromIntent(intent.getExtras(), allSettings, prefs);
if (daemonSetting == null) {
TLog.e(LOG_NAME, "No default daemon can be found.");
return;
}
IDaemonAdapter daemon = daemonSetting.getType().createAdapter(daemonSetting);
// Execute the requested task
DaemonTaskResult result = null;
if (intent.getAction().equals(INTENT_SET_TRANSFER_RATES)) {
result = setTransferRates(daemon, intent.getExtras());
} else if (intent.getAction().equals(INTENT_PAUSE_ALL)) {
result = PauseAllTask.create(daemon).execute();
} else if (intent.getAction().equals(INTENT_RESUME_ALL)) {
result = ResumeAllTask.create(daemon).execute();
} else if (intent.getAction().equals(INTENT_STOP_ALL)) {
result = StopAllTask.create(daemon).execute();
} else if (intent.getAction().equals(INTENT_START_ALL)) {
result = StartAllTask.create(daemon, false).execute();
}
if (result == null) {
return;
}
// Log task result
TLog.d(LOG_NAME, result.toString());
}
private static DaemonSettings parseDaemonFromIntent(Bundle extras, List<DaemonSettings> allSettings, SharedPreferences prefs) {
if (allSettings.size() == 0) {
return null;
}
if (extras != null && extras.containsKey(INTENT_EXTRA_DAEMON)) {
// Explicitly supplied a daemon number; try to parse this
int daemonNumber;
try {
daemonNumber = Integer.parseInt(extras.getString(INTENT_EXTRA_DAEMON));
return allSettings.get(daemonNumber);
} catch (Exception e) {
TLog.e(LOG_NAME, "Invalid daemon number specified: \"" + extras.getString(INTENT_EXTRA_DAEMON) + "\" does not exist.");
return null;
}
}
// No daemon defined explicitly; use the last used daemon
return Preferences.readLastUsedDaemonSettings(prefs, allSettings);
}
private DaemonTaskResult setTransferRates(IDaemonAdapter daemon, Bundle extras) {
int downloadRate;
int uploadRate;
// Parse the extras for the new rates
if (extras == null || !extras.containsKey(INTENT_EXTRA_DOWNLOAD_RATE)) {
TLog.e(LOG_NAME, "Tried to set transfer rates, but no " + INTENT_EXTRA_DOWNLOAD_RATE + " was provided.");
return null;
} else {
downloadRate = extras.getInt(INTENT_EXTRA_DOWNLOAD_RATE);
}
if (extras == null || !extras.containsKey(INTENT_EXTRA_UPLOAD_RATE)) {
TLog.e(LOG_NAME, "Tried to set transfer rates, but no " + INTENT_EXTRA_UPLOAD_RATE + " was provided.");
return null;
} else {
uploadRate = extras.getInt(INTENT_EXTRA_UPLOAD_RATE);
}
return SetTransferRatesTask.create(daemon, uploadRate, downloadRate).execute();
}
}
| Java |
package org.transdroid.util;
import org.transdroid.daemon.util.ITLogger;
import android.util.Log;
/**
* Universal logger class (as srop-in replacement for the default Log).
*
* @author erickok
*
*/
public class TLog {
private static final String LOG_TAG = "Transdroid";
/**
* 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) {
Log.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) {
Log.e(LOG_TAG, self + ": " + msg);
}
/**
* Returns an IDLogger instance that redirects all calls to the
* static methods of TLog - to be used to use TLog as an instance
* in DLog (logging daemon messages).
* @return An Android ITLogger instance
*/
public static ITLogger getInstance() {
return new ITLogger() {
@Override
public void d(String self, String msg) {
TLog.d(self, msg);
}
@Override
public void e(String self, String msg) {
TLog.e(self, msg);
}
};
}
}
| Java |
package org.transdroid.widget;
import org.transdroid.daemon.DaemonSettings;
public class WidgetSettings {
final private int id;
final private DaemonSettings daemonSettings;
final private int refreshInterval;
final private int layoutResourceId;
public WidgetSettings(int id, DaemonSettings daemonSettings, int refreshInterval, int layoutResourceId) {
this.id = id;
this.daemonSettings = daemonSettings;
this.refreshInterval = refreshInterval;
this.layoutResourceId = layoutResourceId;
}
/**
* Returns the unique widget ID
* @return The widget ID as assigned by the AppWidgetManager
*/
public int getId() {
return id;
}
/**
* Returns the daemon settings for this widget
* @return The user-chosen daemon settings object
*/
public DaemonSettings getDaemonSettings() {
return daemonSettings;
}
/**
* Returns the refresh interval
* @return The refresh interval in seconds
*/
public int getRefreshInterval() {
return refreshInterval;
}
/**
* Returns the R.layout resource ID
* @return The resource ID fo the XML layout
*/
public int getLayoutResourceId() {
return layoutResourceId;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.widget;
import org.transdroid.util.TLog;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
public class WidgetSmall extends AppWidgetProvider {
private static final String LOG_NAME = "Small widget";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int id : appWidgetIds) {
TLog.d(LOG_NAME, "Update widget " + id + "?");
if (PreferenceManager.getDefaultSharedPreferences(context).contains(org.transdroid.preferences.Preferences.KEY_WIDGET_DAEMON + id)) {
WidgetService.scheduleUpdates(context, id);
}
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
for (int id : appWidgetIds) {
WidgetService.cancelUpdates(context, id);
}
}
// NOTE: Android 1.5 bug workaround
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
super.onReceive(context, intent);
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.widget;
import org.transdroid.util.TLog;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
public class WidgetMedium extends AppWidgetProvider {
private static final String LOG_NAME = "Medium widget";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int id : appWidgetIds) {
TLog.d(LOG_NAME, "Update widget " + id + "?");
if (PreferenceManager.getDefaultSharedPreferences(context).contains(org.transdroid.preferences.Preferences.KEY_WIDGET_DAEMON + id)) {
WidgetService.scheduleUpdates(context, id);
}
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
for (int id : appWidgetIds) {
WidgetService.cancelUpdates(context, id);
}
}
// NOTE: Android 1.5 bug workaround
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
super.onReceive(context, intent);
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.widget;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ifies.android.sax.Item;
import org.ifies.android.sax.RssParser;
import org.transdroid.R;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskResult;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.util.DLog;
import org.transdroid.gui.LocalTorrent;
import org.transdroid.preferences.Preferences;
import org.transdroid.rss.RssFeedSettings;
import org.transdroid.util.TLog;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.SystemClock;
import android.preference.PreferenceManager;
/**
* A service that updates any running widget by making (synchronous) calls to its assigned
* server daemons. It can start these updates by calling the scheduleUpdate method for every
* newly added widget.
*
* @author erickok
*/
public class WidgetService extends IntentService {
private static final String LOG_NAME = "Widget service";
public static final String INTENT_EXTRAS_WIDGET_ID = "org.transdroid.widget.WIDGET_ID";
private static final Map<Integer, PendingIntent> intents = new HashMap<Integer, PendingIntent>();
public WidgetService() {
super(LOG_NAME);
}
public static void cancelUpdates(Context context, int widgetId) {
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
if (intents.containsKey(widgetId)) {
mgr.cancel(intents.get(widgetId));
}
}
/**
* Repeatedly ask the service to update a service widget, starting directly with the first call
* @param context The application context
* @param int The widget for which to schedule the updates
*/
public static void scheduleUpdates(Context context, int widgetId) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Ensure a PendingIntent for this widget
if (!intents.containsKey(widgetId)) {
Intent intent = new Intent(context, WidgetUpdateReceiver.class);
intent.setData(Uri.parse("widget:" + widgetId)); // This is used to make the intent unique (see http://stackoverflow.com/questions/2844274)
intent.putExtra(WidgetService.INTENT_EXTRAS_WIDGET_ID, widgetId);
intents.put(widgetId, PendingIntent.getBroadcast(context, widgetId, intent, 0));
}
// Schedule a first (directly) and any subsequent updates
int interval = Preferences.readWidgetIntervalSettin(prefs, widgetId) * 1000;
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), interval, intents.get(widgetId));
}
@Override
protected void onHandleIntent(Intent intent) {
// Attach the Android TLog to the daemon logger
DLog.setLogger(TLog.getInstance());
// Retrieve the widget settings
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
List<DaemonSettings> allDaemons = Preferences.readAllDaemonSettings(prefs);
boolean onlyShowTransferring = prefs.getBoolean(Preferences.KEY_PREF_LASTSORTGTZERO, false);
WidgetSettings widget = Preferences.readWidgetSettings(prefs, intent.getIntExtra(INTENT_EXTRAS_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID), allDaemons);
if (widget != null && widget.getDaemonSettings() != null && widget.getDaemonSettings().getType() != null) {
// Also refresh the RSS feed counter?
int newRssCount = -1;
if (widget.getLayoutResourceId() == R.layout.appwidget_small) {
TLog.d(LOG_NAME, "Looking for RSS feed updates");
newRssCount = refreshRssFeedNewItems(prefs);
}
// Retrieve the torrents from the server
TLog.d(LOG_NAME, widget.getDaemonSettings().getHumanReadableIdentifier() + ": Retrieving torrent listing");
WidgetServiceHelper.showMessageTextOnWidget(getApplicationContext(), widget, getText(R.string.connecting));
IDaemonAdapter daemon = widget.getDaemonSettings().getType().createAdapter(widget.getDaemonSettings());
DaemonTaskResult result = RetrieveTask.create(daemon).execute();
if (result instanceof RetrieveTaskSuccessResult) {
// Get the returned torrents
RetrieveTaskSuccessResult success = (RetrieveTaskSuccessResult) result;
List<Torrent> torrents = success.getTorrents();
if (torrents.size() > 0) {
// Show the overall status of the retrieved torrents
WidgetServiceHelper.showTorrentStatisticsOnWidget(getApplicationContext(), widget, torrents, onlyShowTransferring, newRssCount);
} else {
// Set the view to show 'no torrents'
WidgetServiceHelper.showMessageTextOnWidget(getApplicationContext(), widget, getText(R.string.no_torrents));
}
} else {
// Set the error text on the widget
DaemonTaskFailureResult failure = (DaemonTaskFailureResult) result;
WidgetServiceHelper.showMessageTextOnWidget(getApplicationContext(), widget, getText(LocalTorrent.getResourceForDaemonException(failure.getException())));
}
}
}
private static int refreshRssFeedNewItems(SharedPreferences prefs) {
List<RssFeedSettings> feeds = Preferences.readAllRssFeedSettings(prefs);
int unread = 0;
for (RssFeedSettings settings : feeds) {
try {
// Load RSS items
RssParser parser = new RssParser(settings.getUrl());
parser.parse();
if (parser.getChannel() != null) {
// Count items until that last known read item is found again
// Note that the item URL is used as unique identifier
List<Item> items = parser.getChannel().getItems();
Collections.sort(items, Collections.reverseOrder());
for (Item item : items) {
if (settings.getLastNew() == null || item == null || item.getTheLink() == null || item.getTheLink().equals(settings.getLastNew())) {
break;
}
unread++;
}
}
} catch (Exception e) {
// Ignore RSS items that could not be retrieved or parsed
}
}
return unread;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.widget;
import java.util.List;
import org.transdroid.R;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.util.FileSizeConverter;
import org.transdroid.daemon.util.TimespanConverter;
import org.transdroid.gui.Torrents;
import org.transdroid.gui.Transdroid;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.view.View;
import android.widget.RemoteViews;
public class WidgetServiceHelper {
private static void setViewsOnWidget(Context appContext, WidgetSettings widget, RemoteViews views) {
AppWidgetManager manager = AppWidgetManager.getInstance(appContext);
// Set up a refresh intent
Intent intent = new Intent(appContext, WidgetService.class);//.setAction(WidgetService.INTENT_ACTION_REFRESH);
intent.setData(Uri.parse("widget:" + widget.getId())); // This is used to make the intent unique (see http://stackoverflow.com/questions/2844274)
intent.putExtra(WidgetService.INTENT_EXTRAS_WIDGET_ID, widget.getId());
// Set up start intent (on the widget's daemon)
Intent start = new Intent(appContext, Torrents.class);
start.setData(Uri.parse("daemon:" + widget.getDaemonSettings().getIdString())); // This is used to make the intent unique (see http://stackoverflow.com/questions/2844274)
start.putExtra(Transdroid.INTENT_OPENDAEMON, widget.getDaemonSettings().getIdString());
// Attach button handlers
views.setOnClickPendingIntent(R.id.widget_action, PendingIntent.getActivity(appContext, 0, start, 0));
views.setOnClickPendingIntent(R.id.widget_refresh, PendingIntent.getService(appContext, widget.getId(), intent, 0));
manager.updateAppWidget(widget.getId(), views);
}
public static void showMessageTextOnWidget(Context appContext, WidgetSettings widget, CharSequence message) {
RemoteViews views = new RemoteViews(appContext.getPackageName(), widget.getLayoutResourceId());
WidgetServiceHelper.showMessageText(views, message);
setViewsOnWidget(appContext, widget, views);
}
public static void showTorrentStatisticsOnWidget(Context appContext, WidgetSettings widget, List<Torrent> torrents, boolean onlyShowTransferring, int newRssCount) {
RemoteViews views = new RemoteViews(appContext.getPackageName(), widget.getLayoutResourceId());
WidgetServiceHelper.showTorrentStatistics(appContext.getResources(), views, torrents, onlyShowTransferring, newRssCount);
setViewsOnWidget(appContext, widget, views);
}
/**
* Helper function to show a message in the widget views instead of torrent (status) data
* @param resourceId The string resource ID with the text message
*/
private static void showMessageText(RemoteViews views, CharSequence message) {
views.setTextViewText(R.id.widget_message, message);
views.setInt(R.id.widget_message, "setVisibility", View.VISIBLE);
views.setInt(R.id.widget_downloading, "setVisibility", View.GONE);
views.setInt(R.id.widget_eta, "setVisibility", View.GONE);
views.setInt(R.id.widget_other, "setVisibility", View.GONE);
if (views.getLayoutId() == R.layout.appwidget_small) {
views.setInt(R.id.widget_seeding, "setVisibility", View.GONE);
views.setInt(R.id.widget_progress_container, "setVisibility", View.GONE);
views.setProgressBar(R.id.widget_progress, 100, 0, false);
views.setInt(R.id.widget_rssicon, "setVisibility", View.GONE);
views.setInt(R.id.widget_rssnew, "setVisibility", View.GONE);
}
}
/**
* Helper function to show an aggregate over the torrent data inside the widget views
* @param torrent The torrents for which to show statistics
*/
private static void showTorrentStatistics(Resources res, RemoteViews views, List<Torrent> torrents, boolean onlyShowTransferring, int newRssCount) {
int downloading = 0;
int downloadingD = 0;
int downloadingU = 0;
int eta = -1;
int seeding = 0;
int seedingU = 0;
float progress = 0;
int other = 0;
for (Torrent tor : torrents) {
if (tor.getStatusCode() == TorrentStatus.Downloading && (!onlyShowTransferring || tor.getRateDownload() > 0)) {
downloading++;
downloadingD += tor.getRateDownload();
downloadingU += tor.getRateUpload();
progress += tor.getDownloadedPercentage();
eta = Math.max(eta, tor.getEta());
} else if (tor.getStatusCode() == TorrentStatus.Seeding && (!onlyShowTransferring || tor.getRateUpload() > 0)) {
seeding++;
seedingU += tor.getRateUpload();
} else {
other++;
}
}
views.setInt(R.id.widget_message, "setVisibility", View.GONE);
views.setInt(R.id.widget_downloading, "setVisibility", View.VISIBLE);
views.setInt(R.id.widget_eta, "setVisibility", View.VISIBLE);
views.setInt(R.id.widget_other, "setVisibility", View.VISIBLE);
if (views.getLayoutId() == R.layout.appwidget_small) {
views.setInt(R.id.widget_seeding, "setVisibility", View.VISIBLE);
views.setInt(R.id.widget_rssicon, "setVisibility", View.VISIBLE);
views.setInt(R.id.widget_rssnew, "setVisibility", View.VISIBLE);
views.setInt(R.id.widget_progress_container, "setVisibility", View.VISIBLE);
views.setTextViewText(R.id.widget_downloading,
downloading + " " + res.getString(R.string.widget_downloading) + (eta >= 0? " " +
TimespanConverter.getTime(eta, false): (downloading == 0? "": res.getString(R.string.widget_unknowneta))));
views.setTextViewText(R.id.widget_eta,
FileSizeConverter.getSize(downloadingD) + res.getString(R.string.widget_persecond) + "\u2193 " +
FileSizeConverter.getSize(downloadingU) + res.getString(R.string.widget_persecond) + "\u2191");
views.setTextViewText(R.id.widget_seeding,
seeding + " " + res.getString(R.string.widget_seeding) + " " +
FileSizeConverter.getSize(seedingU) + res.getString(R.string.widget_persecond) + "\u2191");
views.setProgressBar(R.id.widget_progress, 100, (int)((progress / downloading) * 100f), false);
views.setTextViewText(R.id.widget_other,
other + " " + res.getString(R.string.widget_other));
views.setTextViewText(R.id.widget_rssnew, newRssCount + " " + res.getString(R.string.widget_new));
} else {
views.setTextViewText(R.id.widget_downloading, downloading + " " + res.getString(R.string.widget_downloading) + " " +
FileSizeConverter.getSize(downloadingD) + res.getString(R.string.widget_persecond) + " - " +
FileSizeConverter.getSize(downloadingU) + res.getString(R.string.widget_persecond) + " " +
res.getString(R.string.widget_downloading_up));
views.setTextViewText(R.id.widget_eta, (eta == -1? res.getString(R.string.widget_unknowneta):
res.getString(R.string.widget_eta) + " " + TimespanConverter.getTime(eta, true)));
views.setTextViewText(R.id.widget_other, seeding + " " + res.getString(R.string.widget_seeding) + " " +
FileSizeConverter.getSize(seedingU) + res.getString(R.string.widget_persecond) + " - " + other + " " +
res.getString(R.string.widget_other));
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.widget;
import java.util.List;
import org.transdroid.R;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.preferences.Preferences;
import org.transdroid.preferences.TransdroidButtonPreference;
import org.transdroid.preferences.TransdroidCheckBoxPreference;
import org.transdroid.preferences.TransdroidEditTextPreference;
import org.transdroid.preferences.TransdroidListPreference;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
/**
* An activity to set up some preferences for a new-to-add home screen widget.
*
* @author erickok
*/
public class WidgetConfigure extends PreferenceActivity {
private int widget = AppWidgetManager.INVALID_APPWIDGET_ID;
private boolean isSmall;
private List<DaemonSettings> allDaemons;
private TransdroidListPreference daemon;
private TransdroidListPreference refresh;
private TransdroidListPreference layout;
private TransdroidButtonPreference addButton;
private String daemonValue = null;
private String refreshValue;
private String layoutValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if they press the back button.
setResult(RESULT_CANCELED);
// For which widget?
if (getIntent() != null && getIntent().hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
widget = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
if (widget == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
return;
}
// Determine if this is a configuration session for a small widget
AppWidgetManager mgr = AppWidgetManager.getInstance(getApplicationContext());
isSmall = mgr.getAppWidgetInfo(widget).provider.getClassName().equals("org.transdroid.widget.WidgetSmall");
// Create the preferences screen here: this takes care of saving/loading, but also contains the ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Load the user preferences (with the available daemons)
allDaemons = Preferences.readAllDaemonSettings(prefs);
String[] allDaemonEntries = new String[allDaemons.size()];
String[] allDaemonValues = new String[allDaemons.size()];
int i = 0;
for (DaemonSettings daemon : allDaemons) {
allDaemonEntries[i] = daemon.getName();
allDaemonValues[i] = daemon.getIdString();
i++;
}
// Are there any configured servers that can be attached to this widget?
if (allDaemons.size() == 0) {
Toast.makeText(this, R.string.no_servers, Toast.LENGTH_SHORT).show();
finish();
return;
}
// Set default values
DaemonSettings lastUsedDaemon = Preferences.readLastUsedDaemonSettings(prefs, allDaemons);
if (lastUsedDaemon != null) {
daemonValue = lastUsedDaemon.getIdString();
}
refreshValue = "86400";
if (isSmall) {
layoutValue = "style_small";
} else {
layoutValue = "style_black";
}
// Save this settings, so that if the user doesn't make any changes, the widget still has the default values being assigned
Editor editor = prefs.edit();
editor.putString(Preferences.KEY_WIDGET_DAEMON + widget, daemonValue);
editor.putString(Preferences.KEY_WIDGET_REFRESH + widget, refreshValue);
editor.putString(Preferences.KEY_WIDGET_LAYOUT + widget, layoutValue);
editor.commit();
// Create preference objects
getPreferenceScreen().setTitle(R.string.pref_search);
// Daemon
daemon = new TransdroidListPreference(this);
daemon.setTitle(R.string.widget_pref_server);
daemon.setKey(Preferences.KEY_WIDGET_DAEMON + widget);
daemon.setEntries(allDaemonEntries);
daemon.setEntryValues(allDaemonValues);
daemon.setDialogTitle(R.string.widget_pref_server);
if (daemonValue != null) {
daemon.setValue(daemonValue);
int daemonId = (daemonValue == ""? 0: Integer.parseInt(daemonValue));
daemon.setSummary(allDaemons.get(daemonId).getName());
}
daemon.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(daemon);
// Refresh
refresh = new TransdroidListPreference(this);
refresh.setTitle(R.string.widget_pref_refresh);
refresh.setKey(Preferences.KEY_WIDGET_REFRESH + widget);
refresh.setEntries(R.array.pref_alarminterval_types);
refresh.setEntryValues(R.array.pref_alarminterval_values);
refresh.setDialogTitle(R.string.widget_pref_refresh);
refresh.setValue(refreshValue);
refresh.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(refresh);
if (!isSmall) {
// Layout
layout = new TransdroidListPreference(this);
layout.setTitle(R.string.widget_pref_layout);
layout.setKey(Preferences.KEY_WIDGET_LAYOUT + widget);
layout.setEntries(R.array.pref_widget_types);
layout.setEntryValues(R.array.pref_widget_values);
layout.setDialogTitle(R.string.widget_pref_layout);
layout.setValue(layoutValue);
layout.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(layout);
}
addButton = new TransdroidButtonPreference(this);
addButton.setTitle(R.string.widget_pref_addwidget);
addButton.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
startWidget();
return true;
}
});
getPreferenceScreen().addItemFromInflater(addButton);
updateDescriptionTexts();
}
private OnPreferenceChangeListener updateHandler = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == daemon) {
daemonValue = (String) newValue;
} else if (preference == refresh) {
refreshValue = (String) newValue;
} else if (preference == layout) {
layoutValue = (String) newValue;
}
updateDescriptionTexts();
// Set the value as usual
return true;
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference)item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference)item).click();
} else if (item instanceof TransdroidEditTextPreference) {
((TransdroidEditTextPreference)item).click();
}
}
private void updateDescriptionTexts() {
int daemonId = (daemonValue == ""? 0: Integer.parseInt(daemonValue));
daemon.setSummary(daemonValue == null? "": allDaemons.get(daemonId).getName());
refresh.setSummary(Preferences.parseArrayEntryFromValue(this, R.array.pref_alarminterval_types, R.array.pref_alarminterval_values, refreshValue));
if (layout != null) {
layout.setSummary(Preferences.parseArrayEntryFromValue(this, R.array.pref_widget_types, R.array.pref_widget_values, layoutValue));
}
}
protected void startWidget() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
WidgetSettings settings = Preferences.readWidgetSettings(prefs, widget, allDaemons);
// Perform a first widget update
/*AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
RemoteViews views = new RemoteViews(getPackageName(), settings.getLayoutResourceId());
appWidgetManager.updateAppWidget(settings.getId(), views);*/
WidgetService.scheduleUpdates(getApplicationContext(), settings.getId());
setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, settings.getId()));
finish();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.widget;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
public class WidgetUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent broadcast) {
int widget = broadcast.getIntExtra(WidgetService.INTENT_EXTRAS_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
Intent intent = new Intent(context, WidgetService.class);//.setAction(WidgetService.INTENT_ACTION_REFRESH);
intent.setData(Uri.parse("widget:" + widget)); // This is used to make the intent unique (see http://stackoverflow.com/questions/2844274)
intent.putExtra(WidgetService.INTENT_EXTRAS_WIDGET_ID, widget);
context.startService(intent);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import android.content.Context;
import android.preference.EditTextPreference;
/**
* Wrapper class for EditTextPreference to expose the onClick() method
*
* @author erickok
*
*/
public class TransdroidEditTextPreference extends EditTextPreference {
public TransdroidEditTextPreference(Context context) { super(context); }
public void click() { onClick(); }
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.R;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.gui.search.SiteSettings;
import org.transdroid.rss.RssFeedSettings;
import ca.seedstuff.transdroid.preferences.SeedstuffSettings;
import com.seedm8.transdroid.preferences.SeedM8Settings;
import com.xirvik.transdroid.preferences.XirvikSettings;
import android.app.ListActivity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* A hybrid adapter that can show Transdroid prefences in a list screen.
*
* @author erickok
*
*/
public class PreferencesAdapter extends BaseAdapter {
public static final String ADD_NEW_XSERVER = "add_new_xserver";
public static final String ADD_NEW_8SERVER = "add_new_8server";
public static final String ADD_NEW_SSERVER = "add_new_sserver";
public static final String ADD_NEW_DAEMON = "add_new_daemon";
public static final String ADD_NEW_WEBSITE = "add_new_website";
public static final String ADD_NEW_RSSFEED = "add_new_rssfeed";
public static final String ADD_EZRSS_FEED = "add_ezrss_feed";
public static final String RSS_SETTINGS = "rss_settings";
public static final String INTERFACE_SETTINGS = "interface_settings";
public static final String CLEAN_SEARCH_HISTORY = "clear_search_history";
public static final String ALARM_SETTINGS = "alarm_settings";
public static final String SET_DEFAULT_SITE = "set_default_site";
public static final String EXPORT_SETTINGS = "export_settings";
public static final String IMPORT_SETTINGS = "import_settings";
private Context context;
private List<Object> items;
/**
* Convenience constructor for a simple listing of the given servers (for server selection, for example)
* @param context The preferences screen
* @param daemons List of existing servers
*/
public PreferencesAdapter(Context context, List<DaemonSettings> daemons) {
this(context, null, null, null, null, daemons, null, null, true, false, false);
}
/**
* Convenience constructor for a the RSS preferences screen
* @param context The preferences screen
* @param feeds List of existing RSS feeds
* @param foo Dummy (unused) parameter to make this constructor's signature unique
*/
public PreferencesAdapter(Context context, List<RssFeedSettings> feeds, int foo) {
this(context, null, null, null, null, null, feeds, null, false, false, true);
}
/**
* Convenience constructor for the main preferences screen
* @param preferencesActivity The preferences screen
* @param xservers All Xirvik server settings
* @param s8servers All SeedM8 server settings
* @param daemons All regular server settings
* @param websites All web-search site settings
*/
public PreferencesAdapter(ListActivity preferencesActivity, List<XirvikSettings> xservers, List<SeedM8Settings> s8servers, List<SeedstuffSettings> sservers, List<DaemonSettings> daemons, List<SiteSettings> websites) {
this(preferencesActivity, preferencesActivity, xservers, s8servers, sservers, daemons, null, websites, true, true, false);
}
private PreferencesAdapter(Context context, ListActivity preferencesActivity, List<XirvikSettings> xservers, List<SeedM8Settings> s8servers, List<SeedstuffSettings> sservers, List<DaemonSettings> daemons, List<RssFeedSettings> feeds, List<SiteSettings> websites, boolean withDaemons, boolean withOthers, boolean withRssFeeds) {
this.context = context;
// Put all 'real' items in a generic list together with the needed buttons and separators
this.items = new ArrayList<Object>();
if (withDaemons) {
this.items.addAll(daemons);
}
if (withOthers) {
this.items.addAll(xservers);
this.items.addAll(s8servers);
this.items.addAll(sservers);
this.items.add(new PreferencesListButton(context, ADD_NEW_DAEMON, R.string.add_new_server));
this.items.add(new XirvikListButton(preferencesActivity, ADD_NEW_XSERVER, R.string.xirvik_add_new_xserver));
this.items.add(new SeedM8ListButton(preferencesActivity, ADD_NEW_8SERVER, R.string.seedm8_add_new_xserver));
this.items.add(new SeedstuffListButton(preferencesActivity, ADD_NEW_SSERVER, R.string.seedstuff_add_new_xserver));
this.items.add(new Divider(context, R.string.pref_search));
this.items.add(new PreferencesListButton(context, SET_DEFAULT_SITE, R.string.pref_setdefault));
this.items.addAll(websites);
this.items.add(new PreferencesListButton(context, ADD_NEW_WEBSITE, R.string.add_new_website));
this.items.add(new Divider(context, R.string.other_settings));
this.items.add(new PreferencesListButton(context, RSS_SETTINGS, R.string.pref_rss_info));
this.items.add(new PreferencesListButton(context, INTERFACE_SETTINGS, R.string.pref_interface));
this.items.add(new PreferencesListButton(context, ALARM_SETTINGS, R.string.pref_alarm));
this.items.add(new PreferencesListButton(context, CLEAN_SEARCH_HISTORY, R.string.pref_clear_search_history));
this.items.add(new PreferencesListButton(context, EXPORT_SETTINGS, R.string.pref_export_settings));
this.items.add(new PreferencesListButton(context, IMPORT_SETTINGS, R.string.pref_import_settings));
}
if (withRssFeeds) {
this.items.addAll(feeds);
this.items.add(new PreferencesListButton(context, ADD_NEW_RSSFEED, R.string.add_new_rssfeed));
this.items.add(new PreferencesListButton(context, ADD_EZRSS_FEED, R.string.pref_ezrss));
}
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
// Always enabled, except when the item is a Divider
return !(getItem(position) instanceof Divider);
}
@Override
/**
* Returns the view for this list item, which is
* a xirvik server,
* a daemon,
* a web search site,
* an RSS feed,
* or one of the buttons or dividers
*/
public View getView(int position, View convertView, ViewGroup parent) {
Object item = getItem(position);
if (item instanceof XirvikSettings) {
// return a Xirvik list view
XirvikSettings xserver = (XirvikSettings) item;
if (convertView == null || !(convertView instanceof XirvikSettingsView)) {
return new XirvikSettingsView(context, xserver);
}
// Reuse view
XirvikSettingsView setView = (XirvikSettingsView) convertView;
setView.SetData(xserver);
return setView;
} else if (item instanceof SeedM8Settings) {
// return a SeedM8 list view
SeedM8Settings s8server = (SeedM8Settings) item;
if (convertView == null || !(convertView instanceof SeedM8SettingsView)) {
return new SeedM8SettingsView(context, s8server);
}
// Reuse view
SeedM8SettingsView setView = (SeedM8SettingsView) convertView;
setView.SetData(s8server);
return setView;
} else if (item instanceof SeedstuffSettings) {
// return a Seedstuff list view
SeedstuffSettings sserver = (SeedstuffSettings) item;
if (convertView == null || !(convertView instanceof SeedstuffSettingsView)) {
return new SeedstuffSettingsView(context, sserver);
}
// Reuse view
SeedstuffSettingsView setView = (SeedstuffSettingsView) convertView;
setView.SetData(sserver);
return setView;
} else if (item instanceof DaemonSettings) {
// return a DaemonSettings list view
DaemonSettings daemon = (DaemonSettings) item;
if (convertView == null || !(convertView instanceof DaemonSettingsView)) {
return new DaemonSettingsView(context, daemon);
}
// Reuse view
DaemonSettingsView setView = (DaemonSettingsView) convertView;
setView.SetData(daemon);
return setView;
} else if (item instanceof SiteSettings) {
// return a SiteSettings list view
SiteSettings site = (SiteSettings) item;
if (convertView == null || !(convertView instanceof SiteSettingsView)) {
return new SiteSettingsView(context, site);
}
// Reuse view
SiteSettingsView setView = (SiteSettingsView) convertView;
setView.SetData(site);
return setView;
} else if (item instanceof RssFeedSettings) {
// return a RssSettings list view
RssFeedSettings rssFeed = (RssFeedSettings) item;
if (convertView == null || !(convertView instanceof RssFeedSettingsView)) {
return new RssFeedSettingsView(context, rssFeed);
}
// Reuse view
RssFeedSettingsView setView = (RssFeedSettingsView) convertView;
setView.SetData(rssFeed);
return setView;
} else if (item instanceof LinearLayout){
// Directly return the button/divider view
return (LinearLayout) item;
}
return null;
}
/**
* A list item representing a Xirvik settings object (by showing its name and an identifier text)
*/
public class XirvikSettingsView extends LinearLayout {
XirvikSettings settings;
public XirvikSettingsView(Context context, XirvikSettings settings) {
super(context);
addView(inflate(context, R.layout.list_item_seedbox_settings, null));
ImageView icon = (ImageView) findViewById(R.id.icon);
icon.setImageResource(R.drawable.xirvik_icon);
this.settings = settings;
SetData(settings);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void SetData(XirvikSettings settings) {
((TextView)findViewById(R.id.title)).setText(settings.getName());
((TextView)findViewById(R.id.summary)).setText(settings.getHumanReadableIdentifier());
}
}
/**
* A list item representing a SeedM8 settings object (by showing its name and an identifier text)
*/
public class SeedM8SettingsView extends LinearLayout {
SeedM8Settings settings;
public SeedM8SettingsView(Context context, SeedM8Settings settings) {
super(context);
addView(inflate(context, R.layout.list_item_seedbox_settings, null));
ImageView icon = (ImageView) findViewById(R.id.icon);
icon.setImageResource(R.drawable.seedm8_icon2);
this.settings = settings;
SetData(settings);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void SetData(SeedM8Settings settings) {
((TextView)findViewById(R.id.title)).setText(settings.getName());
((TextView)findViewById(R.id.summary)).setText(settings.getHumanReadableIdentifier());
}
}
/**
* A list item representing a Seedstuff settings object (by showing its name and an identifier text)
*/
public class SeedstuffSettingsView extends LinearLayout {
SeedstuffSettings settings;
public SeedstuffSettingsView(Context context, SeedstuffSettings settings) {
super(context);
addView(inflate(context, R.layout.list_item_seedbox_settings, null));
ImageView icon = (ImageView) findViewById(R.id.icon);
icon.setImageResource(R.drawable.seedstuff_icon);
this.settings = settings;
SetData(settings);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void SetData(SeedstuffSettings settings) {
((TextView)findViewById(R.id.title)).setText(settings.getName());
((TextView)findViewById(R.id.summary)).setText(settings.getHumanReadableIdentifier());
}
}
/**
* A list item representing a daemon settings object (by showing its name and an identifier text)
*/
public class DaemonSettingsView extends LinearLayout {
DaemonSettings settings;
public DaemonSettingsView(Context context, DaemonSettings settings) {
super(context);
addView(inflate(context, R.layout.list_item_daemon_settings, null));
this.settings = settings;
SetData(settings);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void SetData(DaemonSettings settings) {
((TextView)findViewById(R.id.title)).setText(settings.getName());
((TextView)findViewById(R.id.summary)).setText(settings.getHumanReadableIdentifier());
}
}
/**
* A list item representing a daemon settings object (by showing its name and an identifier text)
*/
public class SiteSettingsView extends LinearLayout {
SiteSettings settings;
public SiteSettingsView(Context context, SiteSettings settings) {
super(context);
addView(inflate(context, R.layout.list_item_daemon_settings, null));
this.settings = settings;
SetData(settings);
}
/**
* Sets the actual texts and images to the visible widgets (fields)
*/
public void SetData(SiteSettings settings) {
((TextView)findViewById(R.id.title)).setText(settings.getName());
((TextView)findViewById(R.id.summary)).setText(settings.getSearchTypeTextResource());
}
}
/**
* A list item representing an RSS feed settings object (by showing its name)
*/
public class RssFeedSettingsView extends LinearLayout {
RssFeedSettings settings;
public RssFeedSettingsView(Context context, RssFeedSettings settings) {
super(context);
addView(inflate(context, R.layout.list_item_daemon_settings, null));
this.settings = settings;
SetData(settings);
}
/**
* Sets the actual text to the visible widget
*/
public void SetData(RssFeedSettings settings) {
((TextView)findViewById(R.id.title)).setText(settings.getName());
((TextView)findViewById(R.id.summary)).setVisibility(GONE);
}
}
/**
* An action button that can be shown inside the list
*/
public class PreferencesListButton extends LinearLayout {
private String key;
/**
* Create a static action button instance, that can be shown in the list screen
* @param context The application context
* @param key The button-unique string to identify clicks
* @param textResourceID The resource of the text to show as the buttons title text
*/
public PreferencesListButton(Context context, String key, int textResourceID) {
super(context);
addView(inflate(context, android.R.layout.simple_list_item_1, null));
this.key = key;
((TextView)findViewById(android.R.id.text1)).setText(textResourceID);
}
/**
* Returns the string identifier that can be used on clicks
* @return The identifier key
*/
public String getKey() {
return key;
}
}
/**
* An button to show inside the list, that allows adding of a new xirvik server as well as to click a '?' button
*/
public class XirvikListButton extends LinearLayout {
private String key;
/**
* Create a static action button instance, that can be shown in the list screen
* @param context The application context
* @param key The button-unique string to identify clicks
* @param textResourceID The resource of the text to show as the buttons title text
*/
public XirvikListButton(final ListActivity context, String key, int textResourceID) {
super(context);
addView(inflate(context, R.layout.list_item_seedbox_pref, null));
this.key = key;
((TextView)findViewById(R.id.add_server)).setText(textResourceID);
ImageButton helpButton = (ImageButton)findViewById(R.id.info);
helpButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
context.showDialog(PreferencesMain.DIALOG_XIRVIK_INFO);
}
});
helpButton.setFocusable(false);
}
/**
* Returns the string identifier that can be used on clicks
* @return The identifier key
*/
public String getKey() {
return key;
}
}
/**
* An button to show inside the list, that allows adding of a new seedm8 server as well as to click a '?' button
*/
public class SeedM8ListButton extends LinearLayout {
private String key;
/**
* Create a static action button instance, that can be shown in the list screen
* @param preferencesActivity The application context
* @param key The button-unique string to identify clicks
* @param textResourceID The resource of the text to show as the buttons title text
*/
public SeedM8ListButton(final ListActivity preferencesActivity, String key, int textResourceID) {
super(preferencesActivity);
addView(inflate(preferencesActivity, R.layout.list_item_seedbox_pref, null));
this.key = key;
((TextView)findViewById(R.id.add_server)).setText(textResourceID);
ImageButton helpButton = (ImageButton)findViewById(R.id.info);
helpButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
preferencesActivity.showDialog(PreferencesMain.DIALOG_SEEDM8_INFO);
}
});
helpButton.setFocusable(false);
}
/**
* Returns the string identifier that can be used on clicks
* @return The identifier key
*/
public String getKey() {
return key;
}
}
/**
* An button to show inside the list, that allows adding of a new seedstuff server as well as to click a '?' button
*/
public class SeedstuffListButton extends LinearLayout {
private String key;
/**
* Create a static action button instance, that can be shown in the list screen
* @param preferencesActivity The application context
* @param key The button-unique string to identify clicks
* @param textResourceID The resource of the text to show as the buttons title text
*/
public SeedstuffListButton(final ListActivity preferencesActivity, String key, int textResourceID) {
super(preferencesActivity);
addView(inflate(preferencesActivity, R.layout.list_item_seedbox_pref, null));
this.key = key;
((TextView)findViewById(R.id.add_server)).setText(textResourceID);
ImageButton helpButton = (ImageButton)findViewById(R.id.info);
helpButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
preferencesActivity.showDialog(PreferencesMain.DIALOG_SEEDSTUFF_INFO);
}
});
helpButton.setFocusable(false);
}
/**
* Returns the string identifier that can be used on clicks
* @return The identifier key
*/
public String getKey() {
return key;
}
}
/**
* A list divider (with the same look as a PreferenceCategory), showing a simple text *
*/
public class Divider extends LinearLayout {
public Divider(Context context, int textResourceID) {
super(context);
addView(inflate(context, R.layout.list_item_preferences_divider, null));
((TextView)findViewById(R.id.title)).setText(textResourceID);
}
}
}
| Java |
package org.transdroid.preferences;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.transdroid.daemon.util.HttpHelper;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
public class ImportExport {
public static final String DEFAULT_SETTINGS_DIR = Environment.getExternalStorageDirectory().toString() + "/Transdroid";
public static final String DEFAULT_SETTINGS_FILENAME = "/settings.json";
public static final File DEFAULT_SETTINGS_FILE = new File(DEFAULT_SETTINGS_DIR + DEFAULT_SETTINGS_FILENAME);
/**
* Synchronously writes the user preferences on servers, web searches and
* RSS feeds to a file in JSON format.
* @param settingsFile The file to write the settings to
* @throws FileNotFoundException Thrown when the settings file doesn't exist
* @throws JSONException Thrown when the file did not contain valid JSON content
*/
public static void importSettings(SharedPreferences prefs, File settingsFile) throws FileNotFoundException, JSONException {
Editor editor = prefs.edit();
// Read the settings file
String raw = HttpHelper.ConvertStreamToString(new FileInputStream(settingsFile));
JSONObject json = new JSONObject(raw);
if (json.has("servers")) {
// Clean old servers
int j = 0;
String postfixj = "";
while (prefs.contains(Preferences.KEY_PREF_ADDRESS + postfixj)) {
editor.remove(Preferences.KEY_PREF_NAME + postfixj);
editor.remove(Preferences.KEY_PREF_DAEMON + postfixj);
editor.remove(Preferences.KEY_PREF_ADDRESS + postfixj);
editor.remove(Preferences.KEY_PREF_PORT + postfixj);
editor.remove(Preferences.KEY_PREF_AUTH + postfixj);
editor.remove(Preferences.KEY_PREF_USER + postfixj);
editor.remove(Preferences.KEY_PREF_PASS + postfixj);
editor.remove(Preferences.KEY_PREF_EXTRAPASS + postfixj);
editor.remove(Preferences.KEY_PREF_FOLDER + postfixj);
editor.remove(Preferences.KEY_PREF_ALARMFINISHED + postfixj);
editor.remove(Preferences.KEY_PREF_ALARMNEW + postfixj);
editor.remove(Preferences.KEY_PREF_OS + postfixj);
editor.remove(Preferences.KEY_PREF_DOWNLOADDIR + postfixj);
editor.remove(Preferences.KEY_PREF_FTPURL + postfixj);
editor.remove(Preferences.KEY_PREF_SSL + postfixj);
editor.remove(Preferences.KEY_PREF_SSL_TRUST_ALL + postfixj);
editor.remove(Preferences.KEY_PREF_SSL_TRUST_KEY + postfixj);
j++;
postfixj = Integer.toString(j);
}
// Import servers
JSONArray servers = json.getJSONArray("servers");
for (int i = 0; i < servers.length(); i++) {
JSONObject server = servers.getJSONObject(i);
String postfix = (i == 0? "": Integer.toString(i));
if (server.has("name")) editor.putString(Preferences.KEY_PREF_NAME + postfix, server.getString("name"));
if (server.has("type")) editor.putString(Preferences.KEY_PREF_DAEMON + postfix, server.getString("type"));
if (server.has("host")) editor.putString(Preferences.KEY_PREF_ADDRESS + postfix, server.getString("host"));
if (server.has("port")) editor.putString(Preferences.KEY_PREF_PORT + postfix, server.getString("port"));
if (server.has("use_auth")) editor.putBoolean(Preferences.KEY_PREF_AUTH + postfix, server.getBoolean("use_auth"));
if (server.has("username")) editor.putString(Preferences.KEY_PREF_USER + postfix, server.getString("username"));
if (server.has("password")) editor.putString(Preferences.KEY_PREF_PASS + postfix, server.getString("password"));
if (server.has("extra_password")) editor.putString(Preferences.KEY_PREF_EXTRAPASS + postfix, server.getString("extra_password"));
if (server.has("folder")) editor.putString(Preferences.KEY_PREF_FOLDER + postfix, server.getString("folder"));
if (server.has("download_alarm")) editor.putBoolean(Preferences.KEY_PREF_ALARMFINISHED + postfix, server.getBoolean("download_alarm"));
if (server.has("new_torrent_alarm")) editor.putBoolean(Preferences.KEY_PREF_ALARMNEW + postfix, server.getBoolean("new_torrent_alarm"));
if (server.has("os_type")) editor.putString(Preferences.KEY_PREF_OS + postfix, server.getString("os_type"));
if (server.has("downloads_dir")) editor.putString(Preferences.KEY_PREF_DOWNLOADDIR + postfix, server.getString("downloads_dir"));
if (server.has("base_ftp_url")) editor.putString(Preferences.KEY_PREF_FTPURL + postfix, server.getString("base_ftp_url"));
if (server.has("ssl")) editor.putBoolean(Preferences.KEY_PREF_SSL + postfix, server.getBoolean("ssl"));
if (server.has("ssl_accept_all")) editor.putBoolean(Preferences.KEY_PREF_SSL_TRUST_ALL + postfix, server.getBoolean("ssl_accept_all"));
if (server.has("ssl_trust_key")) editor.putString(Preferences.KEY_PREF_SSL_TRUST_KEY + postfix, server.getString("ssl_trust_key"));
}
}
if (json.has("websites")) {
// Clean old web search sites
int j = 0;
String postfixj = "0";
while (prefs.contains(Preferences.KEY_PREF_WEBURL + postfixj)) {
editor.remove(Preferences.KEY_PREF_WEBSITE + postfixj);
editor.remove(Preferences.KEY_PREF_WEBURL + postfixj);
j++;
postfixj = Integer.toString(j);
}
// Import web search sites
JSONArray sites = json.getJSONArray("websites");
for (int i = 0; i < sites.length(); i++) {
JSONObject site = sites.getJSONObject(i);
String postfix = Integer.toString(i);
if (site.has("name")) editor.putString(Preferences.KEY_PREF_WEBSITE + postfix, site.getString("name"));
if (site.has("url")) editor.putString(Preferences.KEY_PREF_WEBURL + postfix, site.getString("url"));
}
}
if (json.has("rssfeeds")) {
// Clean old web search sites
int j = 0;
String postfixj = "0";
while (prefs.contains(Preferences.KEY_PREF_RSSURL + postfixj)) {
editor.remove(Preferences.KEY_PREF_RSSNAME + postfixj);
editor.remove(Preferences.KEY_PREF_RSSURL + postfixj);
editor.remove(Preferences.KEY_PREF_RSSAUTH + postfixj);
editor.remove(Preferences.KEY_PREF_RSSLASTNEW + postfixj);
j++;
postfixj = Integer.toString(j);
}
// Import RSS feeds
JSONArray feeds = json.getJSONArray("rssfeeds");
for (int i = 0; i < feeds.length(); i++) {
JSONObject feed = feeds.getJSONObject(i);
String postfix = Integer.toString(i);
if (feed.has("name")) editor.putString(Preferences.KEY_PREF_RSSNAME + postfix, feed.getString("name"));
if (feed.has("url")) editor.putString(Preferences.KEY_PREF_RSSURL + postfix, feed.getString("url"));
if (feed.has("needs_auth")) editor.putBoolean(Preferences.KEY_PREF_RSSAUTH + postfix, feed.getBoolean("needs_auth"));
if (feed.has("last_seen")) editor.putString(Preferences.KEY_PREF_RSSLASTNEW + postfix, feed.getString("last_seen"));
}
}
// Search settings
editor.putString(Preferences.KEY_PREF_NUMRESULTS, json.getString("search_num_results"));
editor.putString(Preferences.KEY_PREF_SORT, json.getString("search_sort_by"));
// Interface settings
editor.putString(Preferences.KEY_PREF_UIREFRESH, json.getString("ui_refresh_interval"));
editor.putBoolean(Preferences.KEY_PREF_SWIPELABELS, json.getBoolean("ui_swipe_labels"));
editor.putBoolean(Preferences.KEY_PREF_ONLYDL, json.getBoolean("ui_only_show_transferring"));
editor.putBoolean(Preferences.KEY_PREF_HIDEREFRESH, json.getBoolean("ui_hide_refresh"));
editor.putBoolean(Preferences.KEY_PREF_ENABLEADS, json.getBoolean("ui_enable_ads"));
editor.putBoolean(Preferences.KEY_PREF_ASKREMOVE, json.getBoolean("ui_ask_before_remove"));
// Alarm service settings
editor.putBoolean(Preferences.KEY_PREF_ENABLEALARM, json.getBoolean("alarm_enabled"));
editor.putString(Preferences.KEY_PREF_ALARMINT, json.getString("alarm_interval"));
editor.putBoolean(Preferences.KEY_PREF_CHECKRSSFEEDS, json.getBoolean("alarm_check_rss_feeds"));
editor.putBoolean(Preferences.KEY_PREF_ALARMPLAYSOUND, json.getBoolean("alarm_play_sound"));
if (json.has("alarm_sound_uri")) editor.putString(Preferences.KEY_PREF_ALARMSOUNDURI, json.getString("alarm_sound_uri"));
editor.putBoolean(Preferences.KEY_PREF_ALARMVIBRATE, json.getBoolean("alarm_vibrate"));
editor.commit();
}
public static void exportSettings(SharedPreferences prefs, File settingsFile) throws JSONException, IOException {
// Create a single JSON object with all settings
JSONObject json = new JSONObject();
// Add servers
JSONArray servers = new JSONArray();
int i = 0;
String postfixi = "";
while (prefs.contains(Preferences.KEY_PREF_ADDRESS + postfixi)) {
JSONObject server = new JSONObject();
server.put("name", prefs.getString(Preferences.KEY_PREF_NAME + postfixi, null));
server.put("type", prefs.getString(Preferences.KEY_PREF_DAEMON + postfixi, null));
server.put("host", prefs.getString(Preferences.KEY_PREF_ADDRESS + postfixi, null));
server.put("port", prefs.getString(Preferences.KEY_PREF_PORT + postfixi, null));
server.put("use_auth", prefs.getBoolean(Preferences.KEY_PREF_AUTH + postfixi, false));
server.put("username", prefs.getString(Preferences.KEY_PREF_USER + postfixi, null));
server.put("password", prefs.getString(Preferences.KEY_PREF_PASS + postfixi, null));
server.put("extra_password", prefs.getString(Preferences.KEY_PREF_EXTRAPASS + postfixi, null));
server.put("folder", prefs.getString(Preferences.KEY_PREF_FOLDER + postfixi, null));
server.put("download_alarm", prefs.getBoolean(Preferences.KEY_PREF_ALARMFINISHED + postfixi, false));
server.put("new_torrent_alarm", prefs.getBoolean(Preferences.KEY_PREF_ALARMNEW + postfixi, false));
server.put("os_type", prefs.getString(Preferences.KEY_PREF_OS + postfixi, null));
server.put("downloads_dir", prefs.getString(Preferences.KEY_PREF_DOWNLOADDIR + postfixi, null));
server.put("base_ftp_url", prefs.getString(Preferences.KEY_PREF_FTPURL + postfixi, null));
server.put("ssl", prefs.getBoolean(Preferences.KEY_PREF_SSL + postfixi, false));
server.put("ssl_accept_all", prefs.getBoolean(Preferences.KEY_PREF_SSL_TRUST_ALL + postfixi, false));
server.put("ssl_trust_key", prefs.getString(Preferences.KEY_PREF_SSL_TRUST_KEY + postfixi, null));
servers.put(server);
i++;
postfixi = Integer.toString(i);
}
json.put("servers", servers);
// Add web search sites
JSONArray sites = new JSONArray();
int j = 0;
String postfixj = "0";
while (prefs.contains(Preferences.KEY_PREF_WEBURL + postfixj)) {
JSONObject site = new JSONObject();
site.put("name", prefs.getString(Preferences.KEY_PREF_WEBSITE + postfixj, null));
site.put("url", prefs.getString(Preferences.KEY_PREF_WEBURL + postfixj, null));
sites.put(site);
j++;
postfixj = Integer.toString(j);
}
json.put("websites", sites);
// Add RSS feeds
JSONArray feeds = new JSONArray();
int k = 0;
String postfixk = "0";
while (prefs.contains(Preferences.KEY_PREF_RSSURL + postfixk)) {
JSONObject feed = new JSONObject();
feed.put("name", prefs.getString(Preferences.KEY_PREF_RSSNAME + postfixk, null));
feed.put("url", prefs.getString(Preferences.KEY_PREF_RSSURL + postfixk, null));
feed.put("needs_auth", prefs.getBoolean(Preferences.KEY_PREF_RSSAUTH + postfixk, false));
feed.put("last_seen", prefs.getString(Preferences.KEY_PREF_RSSLASTNEW + postfixk, null));
feeds.put(feed);
k++;
postfixk = Integer.toString(k);
}
json.put("rssfeeds", feeds);
// Search settings
json.put("search_num_results", prefs.getString(Preferences.KEY_PREF_NUMRESULTS, "25"));
json.put("search_sort_by", prefs.getString(Preferences.KEY_PREF_SORT, Preferences.KEY_PREF_SEEDS));
// Interface settings
json.put("ui_refresh_interval", prefs.getString(Preferences.KEY_PREF_UIREFRESH, "-1"));
json.put("ui_swipe_labels", prefs.getBoolean(Preferences.KEY_PREF_SWIPELABELS, false));
json.put("ui_only_show_transferring", prefs.getBoolean(Preferences.KEY_PREF_ONLYDL, false));
json.put("ui_hide_refresh", prefs.getBoolean(Preferences.KEY_PREF_HIDEREFRESH, false));
json.put("ui_ask_before_remove", prefs.getBoolean(Preferences.KEY_PREF_ASKREMOVE, true));
json.put("ui_enable_ads", prefs.getBoolean(Preferences.KEY_PREF_ENABLEADS, true));
// Alarm service settings
json.put("alarm_enabled", prefs.getBoolean(Preferences.KEY_PREF_ENABLEALARM, false));
json.put("alarm_interval", prefs.getString(Preferences.KEY_PREF_ALARMINT, "600000"));
json.put("alarm_check_rss_feeds", prefs.getBoolean(Preferences.KEY_PREF_CHECKRSSFEEDS, false));
json.put("alarm_play_sound", prefs.getBoolean(Preferences.KEY_PREF_ALARMPLAYSOUND, false));
json.put("alarm_sound_uri", prefs.getString(Preferences.KEY_PREF_ALARMSOUNDURI, null));
json.put("alarm_vibrate", prefs.getBoolean(Preferences.KEY_PREF_ALARMVIBRATE, false));
// Serialize the JSON object to a file
if (settingsFile.exists()) {
settingsFile.delete();
}
settingsFile.getParentFile().mkdirs();
settingsFile.createNewFile();
FileWriter writer = new FileWriter(settingsFile);
writer.write(json.toString(2));
writer.flush();
writer.close();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.json.JSONException;
import org.transdroid.R;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.gui.search.SiteSettings;
import org.transdroid.gui.search.TorrentSearchHistoryProvider;
import org.transdroid.gui.util.ActivityUtil;
import org.transdroid.preferences.PreferencesAdapter.PreferencesListButton;
import org.transdroid.preferences.PreferencesAdapter.SeedM8ListButton;
import org.transdroid.preferences.PreferencesAdapter.SeedstuffListButton;
import org.transdroid.preferences.PreferencesAdapter.XirvikListButton;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import ca.seedstuff.transdroid.preferences.PreferencesSeedstuffServer;
import ca.seedstuff.transdroid.preferences.SeedstuffSettings;
import com.seedm8.transdroid.preferences.PreferencesSeedM8Server;
import com.seedm8.transdroid.preferences.SeedM8Settings;
import com.xirvik.transdroid.preferences.PreferencesXirvikServer;
import com.xirvik.transdroid.preferences.XirvikSettings;
/**
* Provides an activity to edit and store the user preferences of the Transdroid application.
*
* @author erickok
*
*/
public class PreferencesMain extends ListActivity {
private static final int MENU_SET_DEFAULT_ID = 0;
private static final int MENU_REMOVE_ID = 1;
static final int DIALOG_XIRVIK_INFO = 0;
static final int DIALOG_SEEDM8_INFO = 1;
private static final int DIALOG_SET_DEFAULT_SITE = 2;
private static final int DIALOG_IMPORT_SETTINGS = 3;
private static final int DIALOG_EXPORT_SETTINGS = 4;
private static final int DIALOG_INSTALL_FILE_MANAGER = 5;
static final int DIALOG_SEEDSTUFF_INFO = 6;
private final static String PICK_DIRECTORY_INTENT = "org.openintents.action.PICK_DIRECTORY";
private final static String PICK_FILE_INTENT = "org.openintents.action.PICK_FILE";
private final static Uri OIFM_MARKET_URI = Uri.parse("market://search?q=pname:org.openintents.filemanager");
public static final int DIRECTORY_REQUEST_CODE = 1;
public static final int FILE_REQUEST_CODE = 2;
private PreferencesAdapter adapter;
private SharedPreferences prefs;
private SiteSettings currentdefaultsite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Make sure a context menu is created on long-presses
registerForContextMenu(getListView());
buildAdapter();
}
private void buildAdapter() {
// Build a list of server and search site settings objects to show
List<XirvikSettings> xservers = Preferences.readAllXirvikSettings(prefs);
List<SeedM8Settings> s8servers = Preferences.readAllSeedM8Settings(prefs);
List<SeedstuffSettings> sservers = Preferences.readAllSeedstuffSettings(prefs);
List<DaemonSettings> daemons = Preferences.readAllNormalDaemonSettings(prefs);
List<SiteSettings> websites = Preferences.readAllWebSearchSiteSettings(prefs);
currentdefaultsite = Preferences.readDefaultSearchSiteSettings(prefs);
// Set the list items
adapter = new PreferencesAdapter(this, xservers, s8servers, sservers, daemons, websites);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action depending on the clicked list item (note that dividers are ignored)
Object item = getListAdapter().getItem(position);
// Handle button clicks first
if (item instanceof XirvikListButton) {
// What is the max current xirvik settings ID number?
int max = 0;
while (prefs.contains(Preferences.KEY_PREF_XSERVER + (max == 0? "": Integer.toString(max)))) {
max++;
}
// Start a new xirvik server settings screen
Intent i = new Intent(this, PreferencesXirvikServer.class);
i.putExtra(PreferencesXirvikServer.PREFERENCES_XSERVER_KEY, (max == 0? "": Integer.toString(max)));
startActivityForResult(i, 0);
} else if (item instanceof SeedM8ListButton) {
// What is the max current seedm8 settings ID number?
int max = 0;
while (prefs.contains(Preferences.KEY_PREF_8SERVER + (max == 0? "": Integer.toString(max)))) {
max++;
}
// Start a new seedm8 server settings screen
Intent i = new Intent(this, PreferencesSeedM8Server.class);
i.putExtra(PreferencesSeedM8Server.PREFERENCES_8SERVER_KEY, (max == 0? "": Integer.toString(max)));
startActivityForResult(i, 0);
} else if (item instanceof SeedstuffListButton) {
// What is the max current seedstuff settings ID number?
int max = 0;
while (prefs.contains(Preferences.KEY_PREF_SUSER + (max == 0? "": Integer.toString(max)))) {
max++;
}
// Start a new seedstuff server settings screen
Intent i = new Intent(this, PreferencesSeedstuffServer.class);
i.putExtra(PreferencesSeedstuffServer.PREFERENCES_SSERVER_KEY, (max == 0? "": Integer.toString(max)));
startActivityForResult(i, 0);
} else if (item instanceof PreferencesListButton) {
PreferencesListButton button = (PreferencesListButton) item;
if (button.getKey().equals(PreferencesAdapter.ADD_NEW_DAEMON)) {
// What is the max current server ID number?
int max = 0;
while (prefs.contains(Preferences.KEY_PREF_ADDRESS + (max == 0? "": Integer.toString(max)))) {
max++;
}
// Start a new server daemon settings screen
Intent i = new Intent(this, PreferencesServer.class);
i.putExtra(PreferencesServer.PREFERENCES_SERVER_KEY, (max == 0? "": Integer.toString(max)));
startActivityForResult(i, 0);
} else if (button.getKey().equals(PreferencesAdapter.ADD_NEW_WEBSITE)) {
// What is the max current site ID number?
int max = 0;
while (prefs.contains(Preferences.KEY_PREF_WEBURL + Integer.toString(max))) {
max++;
}
// Start a new web site settings screen
Intent i = new Intent(this, PreferencesWebSearch.class);
i.putExtra(PreferencesWebSearch.PREFERENCES_WEBSITE_KEY, Integer.toString(max));
startActivityForResult(i, 0);
} else if (button.getKey().equals(PreferencesAdapter.RSS_SETTINGS)) {
startActivity(new Intent(this, PreferencesRss.class));
} else if (button.getKey().equals(PreferencesAdapter.INTERFACE_SETTINGS)) {
startActivity(new Intent(this, PreferencesInterface.class));
} else if (button.getKey().equals(PreferencesAdapter.CLEAN_SEARCH_HISTORY)) {
// Clear all previous search terms from the search history provider
TorrentSearchHistoryProvider.clearHistory(this);
Toast.makeText(this, R.string.pref_history_cleared, Toast.LENGTH_SHORT).show();
} else if (button.getKey().equals(PreferencesAdapter.SET_DEFAULT_SITE)) {
showDialog(DIALOG_SET_DEFAULT_SITE);
} else if (button.getKey().equals(PreferencesAdapter.ALARM_SETTINGS)) {
startActivity(new Intent(this, PreferencesAlarm.class));
} else if (button.getKey().equals(PreferencesAdapter.IMPORT_SETTINGS)) {
showDialog(DIALOG_IMPORT_SETTINGS);
} else if (button.getKey().equals(PreferencesAdapter.EXPORT_SETTINGS)) {
showDialog(DIALOG_EXPORT_SETTINGS);
}
} else if (item instanceof XirvikSettings) {
// Open the xirvik server settings edit activity for the clicked server
Intent i = new Intent(this, PreferencesXirvikServer.class);
XirvikSettings xserver = (XirvikSettings) item;
i.putExtra(PreferencesXirvikServer.PREFERENCES_XSERVER_KEY, xserver.getIdString());
startActivityForResult(i, 0);
} else if (item instanceof SeedM8Settings) {
// Open the seedm8 server settings edit activity for the clicked server
Intent i = new Intent(this, PreferencesSeedM8Server.class);
SeedM8Settings s8server = (SeedM8Settings) item;
i.putExtra(PreferencesSeedM8Server.PREFERENCES_8SERVER_KEY, s8server.getIdString());
startActivityForResult(i, 0);
} else if (item instanceof SeedstuffSettings) {
// Open the seedstuff server settings edit activity for the clicked server
Intent i = new Intent(this, PreferencesSeedstuffServer.class);
SeedstuffSettings sserver = (SeedstuffSettings) item;
i.putExtra(PreferencesSeedstuffServer.PREFERENCES_SSERVER_KEY, sserver.getIdString());
startActivityForResult(i, 0);
} else if (item instanceof DaemonSettings) {
// Open the daemon settings edit activity for the clicked server
Intent i = new Intent(this, PreferencesServer.class);
DaemonSettings daemon = (DaemonSettings) item;
i.putExtra(PreferencesServer.PREFERENCES_SERVER_KEY, daemon.getIdString());
startActivityForResult(i, 0);
} else if (item instanceof SiteSettings) {
SiteSettings website = (SiteSettings) item;
if (website.isWebSearch()) {
// Open the site settings edit activity for the clicked website
Intent i = new Intent(this, PreferencesWebSearch.class);
i.putExtra(PreferencesWebSearch.PREFERENCES_WEBSITE_KEY, website.getKey());
startActivityForResult(i, 0);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case DIRECTORY_REQUEST_CODE:
// Did we receive a directory name?
if (data != null && data.getData() != null && data.getData().toString() != "") {
if (!canReadWriteToExternalStorage(false)) {
Toast.makeText(PreferencesMain.this, R.string.error_media_not_available, Toast.LENGTH_LONG).show();
return;
}
String path = data.getData().toString().substring("file://".length()) + ImportExport.DEFAULT_SETTINGS_FILENAME;
doExport(new File(path));
}
break;
case FILE_REQUEST_CODE:
// Did we receive a file name?
if (data != null && data.getData() != null && data.getData().toString() != "") {
if (!canReadWriteToExternalStorage(false)) {
Toast.makeText(PreferencesMain.this, R.string.error_media_not_available, Toast.LENGTH_LONG).show();
return;
}
String file = data.getData().toString().substring("file://".length());
doImport(new File(file));
}
break;
default:
// One of the server settings has been updated: refresh the list
buildAdapter();
break;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
Object selected = adapter.getItem((int) ((AdapterContextMenuInfo) item.getMenuInfo()).id);
if (selected instanceof DaemonSettings) {
if (item.getItemId() == MENU_REMOVE_ID) {
// Remove this daemon configuration and reload this screen
Preferences.removeDaemonSettings(prefs, (DaemonSettings)selected);
buildAdapter();
return true;
}
}
if (selected instanceof XirvikSettings) {
if (item.getItemId() == MENU_REMOVE_ID) {
// Remove this xirvik server configuration and reload this screen
Preferences.removeXirvikSettings(prefs, (XirvikSettings)selected);
buildAdapter();
return true;
}
}
if (selected instanceof SeedM8Settings) {
if (item.getItemId() == MENU_REMOVE_ID) {
// Remove this SeedM8 server configuration and reload this screen
Preferences.removeSeedM8Settings(prefs, (SeedM8Settings)selected);
buildAdapter();
return true;
}
}
if (selected instanceof SeedstuffSettings) {
if (item.getItemId() == MENU_REMOVE_ID) {
// Remove this Seedstuff server configuration and reload this screen
Preferences.removeSeedstuffSettings(prefs, (SeedstuffSettings)selected);
buildAdapter();
return true;
}
}
if (selected instanceof SiteSettings) {
if (item.getItemId() == MENU_REMOVE_ID) {
// Remove this site configuration and reload this screen
Preferences.removeSiteSettings(prefs, (SiteSettings)selected);
buildAdapter();
return true;
} else if (item.getItemId() == MENU_SET_DEFAULT_ID) {
// Set this site as the default search
Preferences.storeLastUsedSearchSiteSettings(this, ((SiteSettings)selected).getKey());
Toast.makeText(this, getResources().getText(R.string.menu_default_site_set_to) + " " + ((SiteSettings)selected).getName(), Toast.LENGTH_SHORT).show();
return true;
}
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Allow removing of daemon and site settings
Object item = adapter.getItem((int) ((AdapterContextMenuInfo)menuInfo).id);
// For XirvikSettings, allow removing of the config
if (item instanceof XirvikSettings) {
menu.add(0, MENU_REMOVE_ID, 0, R.string.menu_remove);
}
// For SeedM8Settings, allow removing of the config
if (item instanceof SeedM8Settings) {
menu.add(0, MENU_REMOVE_ID, 0, R.string.menu_remove);
}
// For SeedstuffSettings, allow removing of the config
if (item instanceof SeedstuffSettings) {
menu.add(0, MENU_REMOVE_ID, 0, R.string.menu_remove);
}
// For DeamonSettings, allow removing of the config
if (item instanceof DaemonSettings) {
menu.add(0, MENU_REMOVE_ID, 0, R.string.menu_remove);
}
// For SiteSettings, show a context menu
if (item instanceof SiteSettings) {
menu.add(0, MENU_SET_DEFAULT_ID, 0, R.string.menu_set_default);
// Allow removal if it is a web search engine (in-app sites cannot be removed)
if (((SiteSettings)item).isWebSearch()) {
menu.add(0, MENU_REMOVE_ID, 0, R.string.menu_remove);
}
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_XIRVIK_INFO:
// Build a dialog with the xirvik info message (with logo and link)
AlertDialog.Builder infoDialog = new AlertDialog.Builder(this);
infoDialog.setView(getLayoutInflater().inflate(R.layout.dialog_xirvik_info, null));
return infoDialog.create();
case DIALOG_SEEDM8_INFO:
// Build a dialog with the seedm8 info message (with logo and link)
AlertDialog.Builder s8infoDialog = new AlertDialog.Builder(this);
s8infoDialog.setView(getLayoutInflater().inflate(R.layout.dialog_seedm8_info, null));
return s8infoDialog.create();
case DIALOG_SEEDSTUFF_INFO:
// Build a dialog with the seedstuff info message (with logo and link)
AlertDialog.Builder sinfoDialog = new AlertDialog.Builder(this);
sinfoDialog.setView(getLayoutInflater().inflate(R.layout.dialog_seedstuff_info, null));
return sinfoDialog.create();
case DIALOG_SET_DEFAULT_SITE:
// Build a dialog with a radio box per available search site
List<SiteSettings> allsites = Preferences.readAllSiteSettings(prefs);
AlertDialog.Builder sitesDialog = new AlertDialog.Builder(this);
sitesDialog.setTitle(R.string.pref_setdefault);
// Determine the ID of the current default site
final String[] sitesTexts = buildSiteListForDialog(allsites);
int i = 0;
for (String siteName : sitesTexts) {
if (currentdefaultsite == null || siteName.equals(currentdefaultsite.getName())) {
break;
}
i++;
}
int activeItem = i;
sitesDialog.setSingleChoiceItems(
sitesTexts, // The strings of different sites
(allsites == null? 0: (activeItem < allsites.size()? activeItem: 0)), // The current selection except when this suddenly doesn't exist any more
new DialogInterface.OnClickListener() {
@Override
// When the site name is clicked (and it is different from current default), set the new default site
public void onClick(DialogInterface dialog, int which) {
List<SiteSettings> allsites = Preferences.readAllSiteSettings(prefs);
currentdefaultsite = allsites.get(which);
Preferences.storeLastUsedSearchSiteSettings(getApplicationContext(), currentdefaultsite.getKey());
removeDialog(DIALOG_SET_DEFAULT_SITE);
}
});
return sitesDialog.create();
case DIALOG_IMPORT_SETTINGS:
Builder importDialog = new AlertDialog.Builder(this);
importDialog.setTitle(R.string.pref_import_settings);
importDialog.setMessage(getText(R.string.pref_import_settings_info) + " " + ImportExport.DEFAULT_SETTINGS_FILE);
importDialog.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
dismissDialog(DIALOG_IMPORT_SETTINGS);
if (!canReadWriteToExternalStorage(false)) {
Toast.makeText(PreferencesMain.this, R.string.error_media_not_available, Toast.LENGTH_LONG).show();
return;
}
doImport(ImportExport.DEFAULT_SETTINGS_FILE);
}
});
importDialog.setNeutralButton(R.string.pref_import_settings_pick, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Test to see if a file manager is available that can handle the PICK_FILE intent, such as IO File Manager
Intent pick = new Intent(PICK_FILE_INTENT);
if (ActivityUtil.isIntentAvailable(PreferencesMain.this, pick)) {
// Ask the file manager to allow the user to pick a directory
startActivityForResult(pick, FILE_REQUEST_CODE);
} else {
// Show a message if the user should install OI File Manager for this feature
showDialog(DIALOG_INSTALL_FILE_MANAGER);
}
}
});
importDialog.setNegativeButton(android.R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
dismissDialog(DIALOG_IMPORT_SETTINGS);
}
});
return importDialog.create();
case DIALOG_EXPORT_SETTINGS:
Builder exportDialog = new AlertDialog.Builder(this);
exportDialog.setTitle(R.string.pref_export_settings);
exportDialog.setMessage(getText(R.string.pref_export_settings_info) + " " + ImportExport.DEFAULT_SETTINGS_FILE);
exportDialog.setPositiveButton(android.R.string.ok, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
dismissDialog(DIALOG_EXPORT_SETTINGS);
if (!canReadWriteToExternalStorage(false)) {
Toast.makeText(PreferencesMain.this, R.string.error_media_not_available, Toast.LENGTH_LONG).show();
return;
}
doExport(ImportExport.DEFAULT_SETTINGS_FILE);
}
});
exportDialog.setNeutralButton(R.string.pref_export_settings_pick, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Test to see if a file manager is available that can handle the PICK_DIRECTORY intent, such as IO File Manager
Intent pick = new Intent(PICK_DIRECTORY_INTENT);
if (ActivityUtil.isIntentAvailable(PreferencesMain.this, pick)) {
// Ask the file manager to allow the user to pick a directory
startActivityForResult(pick, DIRECTORY_REQUEST_CODE);
} else {
// Show a message if the user should install OI File Manager for this feature
showDialog(DIALOG_INSTALL_FILE_MANAGER);
}
}
});
exportDialog.setNegativeButton(android.R.string.cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
dismissDialog(DIALOG_EXPORT_SETTINGS);
}
});
return exportDialog.create();
case DIALOG_INSTALL_FILE_MANAGER:
return buildInstallDialog(R.string.oifm_not_found, OIFM_MARKET_URI);
}
return super.onCreateDialog(id);
}
/**
* Builds a (reusable) dialog that asks to install some application from the Android market
* @param messageResourceID The message to show to the user
* @param marketUri The application's URI on the Android Market
* @return
*/
private Dialog buildInstallDialog(int messageResourceID, final Uri marketUri) {
AlertDialog.Builder fbuilder = new AlertDialog.Builder(this);
fbuilder.setMessage(messageResourceID);
fbuilder.setCancelable(true);
fbuilder.setPositiveButton(R.string.oifm_install, new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent install = new Intent(Intent.ACTION_VIEW, marketUri);
if (ActivityUtil.isIntentAvailable(getApplicationContext(), install)) {
startActivity(install);
} else {
Toast.makeText(getApplicationContext(), R.string.oifm_nomarket, Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
});
fbuilder.setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return fbuilder.create();
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DIALOG_SET_DEFAULT_SITE:
// Re-populate the dialog adapter with the available sites
List<SiteSettings> allsites = Preferences.readAllSiteSettings(prefs);
AlertDialog sitesDialog = (AlertDialog) dialog;
ListView sitesRadios = sitesDialog.getListView();
String[] sitesTexts = buildSiteListForDialog(allsites);
ArrayAdapter<String> sitesList = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice, android.R.id.text1, sitesTexts);
sitesRadios.setAdapter(sitesList);
// Determine the ID of the current default
int i = 0;
for (String siteName : sitesTexts) {
if (currentdefaultsite == null || siteName.equals(currentdefaultsite.getName())) {
break;
}
i++;
}
// Also pre-select the current default site
int labelSelected = (allsites == null? 0: (i < allsites.size()? i: 0)); // Prevent going out of bounds
sitesRadios.clearChoices();
sitesRadios.setItemChecked(labelSelected, true);
sitesRadios.setSelection(labelSelected);
break;
}
}
private String[] buildSiteListForDialog(List<SiteSettings> allsites) {
String[] sites = new String[allsites.size()];
for (int i = 0; i < allsites.size(); i++) {
sites[i] = allsites.get(i).getName();
}
return sites;
}
private boolean canReadWriteToExternalStorage(boolean needsWriteAccess) {
// Check access to SD card (for import/export)
if (needsWriteAccess) {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
} else {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY) ||
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
}
private void doImport(File settingsFile) {
try {
ImportExport.importSettings(PreferenceManager.getDefaultSharedPreferences(PreferencesMain.this), settingsFile);
buildAdapter();
Toast.makeText(PreferencesMain.this, R.string.pref_import_settings_success, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(PreferencesMain.this, R.string.error_no_valid_settings_file, Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
Toast.makeText(PreferencesMain.this, R.string.error_file_not_found, Toast.LENGTH_SHORT).show();
}
}
private void doExport(File settingsFile) {
try {
Toast.makeText(PreferencesMain.this, R.string.pref_export_settings_success, Toast.LENGTH_SHORT).show();
ImportExport.exportSettings(PreferenceManager.getDefaultSharedPreferences(PreferencesMain.this), settingsFile);
} catch (JSONException e) {
Toast.makeText(PreferencesMain.this, R.string.error_no_valid_settings_file, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(PreferencesMain.this, R.string.error_media_not_available, Toast.LENGTH_SHORT).show();
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import org.ifies.android.sax.Item;
import org.ifies.android.sax.RssParser;
import org.transdroid.R;
import org.transdroid.gui.rss.RssItemListAdapter;
import org.transdroid.util.TLog;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class EzRssFeedBuilder extends ListActivity implements Runnable {
private static final String LOG_NAME = "RSS listing";
private static final String EZRSS_URL = "http://ezrss.it/search/index.php?show_name=%s%s&date=&quality=%s%s&release_group=%s&mode=rss";
private static final String EZRSS_URL_SHOWNAME_EXACT = "&show_name_exact=true";
private static final String EZRSS_URL_QUALITY_EXACT = "&quality_exact=true";
private static final long TIMER_DELAY = 750;
private TextView empty;
private EditText showname, quality, group;
private CheckBox shownameExact, qualityExact;
private Button save, dismiss;
private Thread timer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_ezrss_feedbuilder);
registerForContextMenu(findViewById(android.R.id.list));
empty = (TextView) findViewById(android.R.id.empty);
showname = (EditText) findViewById(R.id.ezrss_showname);
quality = (EditText) findViewById(R.id.ezrss_quality);
group = (EditText) findViewById(R.id.ezrss_group);
shownameExact = (CheckBox) findViewById(R.id.ezrss_showname_exact);
qualityExact = (CheckBox) findViewById(R.id.ezrss_quality_exact);
save = (Button) findViewById(R.id.ezrss_save);
dismiss = (Button) findViewById(R.id.ezrss_dismiss);
showname.addTextChangedListener(queryChangedListener);
quality.addTextChangedListener(queryChangedListener);
group.addTextChangedListener(queryChangedListener);
shownameExact.setOnCheckedChangeListener(queryChangedListener2);
qualityExact.setOnCheckedChangeListener(queryChangedListener2);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Look for the last RSS feed setting
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int i = 0;
String nextUrl = Preferences.KEY_PREF_RSSURL + Integer.toString(i);
while (prefs.contains(nextUrl)) {
i++;
nextUrl = Preferences.KEY_PREF_RSSURL + Integer.toString(i);
}
// Store an RSS feed setting for this ezRSS feed
Editor editor = prefs.edit();
editor.putString(Preferences.KEY_PREF_RSSNAME + Integer.toString(i), showname.getText().toString());
editor.putString(nextUrl, getUrlForQuery());
editor.commit();
finish();
}
});
dismiss.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
/**
* Refreshes the example feed on text changes (with delay)
*/
private TextWatcher queryChangedListener = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
timer = new Thread(EzRssFeedBuilder.this);
timer.start();
updateWidgets(false, getText(R.string.pref_ezrss_enter).toString(), showname.getText().toString().trim().equals(""));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (timer != null && timer.isAlive()) {
timer.interrupt();
}
}
@Override
public void afterTextChanged(Editable s) {}
};
private OnCheckedChangeListener queryChangedListener2 = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateQuery();
}
};
/**
* Implements a small timer to delay the loading of the example RSS feed
*/
@Override
public void run() {
try {
Thread.sleep(TIMER_DELAY);
// If not interrupted...
runOnUiThread(new Runnable() {
@Override
public void run() {
// Update the example results
updateQuery();
}
});
} catch (InterruptedException e) {
}
}
/**
* Returns the ezRSS feed URL for the given query, consisting of name, quality and group
* @return The URL address of the feed as String
*/
private String getUrlForQuery() {
return String.format(EZRSS_URL,
URLEncoder.encode(showname.getText().toString()),
(shownameExact.isChecked()? EZRSS_URL_SHOWNAME_EXACT: ""),
URLEncoder.encode(quality.getText().toString()),
(qualityExact.isChecked()? EZRSS_URL_QUALITY_EXACT: ""),
URLEncoder.encode(group.getText().toString()));
}
private void updateQuery() {
if (showname.getText().toString().trim().equals("")) {
// Not even a show name given
updateWidgets(false, getText(R.string.pref_ezrss_enter).toString(), false);
return;
}
final String url = getUrlForQuery();
// Set the user message to Loading...
setProgressBarIndeterminate(true);
updateWidgets(false, getText(R.string.pref_ezrss_loading).toString(), true);
final Handler retrieveHandler = new Handler() {
@SuppressWarnings("unchecked")
@Override
public void handleMessage(Message msg) {
// Not loading any more, turn off status indicator
setProgressBarIndeterminate(false);
// Error?
if (msg.what == -1) {
String errorMessage = ((Exception)msg.obj).getMessage();
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show();
updateWidgets(false, errorMessage, true);
return;
}
// The list of items is contained in the message obj
List<Item> items = (List<Item>) msg.obj;
if (items == null || items.size() == 0) {
updateWidgets(false, getText(R.string.pref_ezrss_noresults).toString(), true);
} else {
setListAdapter(new RssItemListAdapter(EzRssFeedBuilder.this, null, items, false, null));
updateWidgets(true, "", true);
}
}
};
// Asynchronous getting of the RSS items
new Thread() {
@Override
public void run() {
try {
// Load RSS items
RssParser parser = new RssParser(url);
parser.parse();
if (parser.getChannel() == null) {
throw new Exception(getResources().getString(R.string.error_norssfeed));
}
List<Item> items = parser.getChannel().getItems();
Collections.sort(items, Collections.reverseOrder());
// Return the list of items
TLog.d(LOG_NAME, "ezRSS feed for '" + showname.getText() + "' has " + items.size() + " messages");
Message msg = Message.obtain();
msg.what = 1;
msg.obj = items;
retrieveHandler.sendMessage(msg);
} catch (Exception e) {
// Return the error to the callback
TLog.d(LOG_NAME, e.toString());
Message msg = Message.obtain();
msg.what = -1;
msg.obj = e;
retrieveHandler.sendMessage(msg);
}
}
}.start();
}
private void updateWidgets(boolean hasResults, String message, boolean hasQuery) {
if (!hasResults) {
// No results (yet), show the message to the user
empty.setText(message);
setListAdapter(null);
}
save.setEnabled(hasQuery);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import android.content.Context;
import android.preference.ListPreference;
/**
* Wrapper class for ListPreference to expose the onClick() method
*
* @author erickok
*
*/
public class TransdroidListPreference extends ListPreference {
public TransdroidListPreference(Context context) { super(context); }
public void click() { onClick(); }
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.transdroid.R;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.OS;
import org.transdroid.daemon.util.HttpHelper;
import org.transdroid.daemon.util.Pair;
import org.transdroid.gui.search.SearchSettings;
import org.transdroid.gui.search.SiteSettings;
import org.transdroid.gui.util.InterfaceSettings;
import org.transdroid.rss.RssFeedSettings;
import org.transdroid.service.AlarmSettings;
import org.transdroid.widget.WidgetSettings;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import ca.seedstuff.transdroid.preferences.SeedstuffSettings;
import com.seedm8.transdroid.preferences.SeedM8Settings;
import com.xirvik.transdroid.preferences.XirvikServerType;
import com.xirvik.transdroid.preferences.XirvikSettings;
/**
* Helper to access and store Transdroid user preferences.
*
* @author erickok
*/
public class Preferences {
// These are all the (base) keys at which preferences are stored on the device
public static final String KEY_PREF_LASTUSED = "transdroid_server_lastused";
public static final String KEY_PREF_SITE = "transdroid_search_site";
public static final String KEY_PREF_LASTSORTBY = "transdroid_interface_lastusedsortby";
public static final String KEY_PREF_LASTSORTORD = "transdroid_interface_lastusedsortorder";
public static final String KEY_PREF_XNAME = "transdroid_xserver_name";
public static final String KEY_PREF_XTYPE = "transdroid_xserver_type";
public static final String KEY_PREF_XSERVER = "transdroid_xserver_server";
public static final String KEY_PREF_XFOLDER = "transdroid_xserver_folder";
public static final String KEY_PREF_XUSER = "transdroid_xserver_user";
public static final String KEY_PREF_XPASS = "transdroid_xserver_pass";
public static final String KEY_PREF_XALARMFINISHED = "transdroid_xserver_alarmfinished";
public static final String KEY_PREF_XALARMNEW = "transdroid_xserver_alarmnew";
public static final String KEY_PREF_8NAME = "transdroid_8server_name";
public static final String KEY_PREF_8SERVER = "transdroid_8server_server";
public static final String KEY_PREF_8USER = "transdroid_8server_user";
public static final String KEY_PREF_8DPASS = "transdroid_8server_dpass";
public static final String KEY_PREF_8DPORT = "transdroid_8server_dprt";
public static final String KEY_PREF_8TPASS = "transdroid_8server_tpass";
public static final String KEY_PREF_8TPORT = "transdroid_8server_tport";
public static final String KEY_PREF_8RPASS = "transdroid_8server_rpass";
public static final String KEY_PREF_8SPASS = "transdroid_8server_spass";
public static final String KEY_PREF_8ALARMFINISHED = "transdroid_8server_alarmfinished";
public static final String KEY_PREF_8ALARMNEW = "transdroid_8server_alarmnew";
public static final String KEY_PREF_SNAME = "transdroid_sserver_name";
public static final String KEY_PREF_SSERVER = "transdroid_sserver_server";
public static final String KEY_PREF_SUSER = "transdroid_sserver_user";
public static final String KEY_PREF_SPASS = "transdroid_sserver_pass";
public static final String KEY_PREF_SALARMFINISHED = "transdroid_sserver_alarmfinished";
public static final String KEY_PREF_SALARMNEW = "transdroid_sserver_alarmnew";
public static final String KEY_PREF_NAME = "transdroid_server_name";
public static final String KEY_PREF_DAEMON = "transdroid_server_daemon";
public static final String KEY_PREF_ADDRESS = "transdroid_server_address";
public static final String KEY_PREF_PORT = "transdroid_server_port";
public static final String KEY_PREF_SSL = "transdroid_server_ssl";
public static final String KEY_PREF_SSL_TRUST_ALL= "transdroid_server_ssl_trust_all";
public static final String KEY_PREF_SSL_TRUST_KEY= "transdroid_server_ssl_trust_key";
public static final String KEY_PREF_FOLDER = "transdroid_server_folder";
public static final String KEY_PREF_AUTH = "transdroid_server_auth";
public static final String KEY_PREF_USER = "transdroid_server_user";
public static final String KEY_PREF_PASS = "transdroid_server_pass";
public static final String KEY_PREF_EXTRAPASS = "transdroid_server_extrapass";
public static final String KEY_PREF_OS = "transdroid_server_os";
public static final String KEY_PREF_DOWNLOADDIR = "transdroid_server_downloaddir";
public static final String KEY_PREF_FTPURL = "transdroid_server_ftpurl";
public static final String KEY_PREF_TIMEOUT = "transdroid_server_timeout";
public static final String KEY_PREF_ALARMFINISHED= "transdroid_server_alarmfinished";
public static final String KEY_PREF_ALARMNEW = "transdroid_server_alarmnew";
public static final String KEY_PREF_WEBSITE = "transdroid_website_name";
public static final String KEY_PREF_WEBURL = "transdroid_website_url";
public static final String KEY_PREF_DEF_SITE = "site_isohunt"; // Default site adapter
public static final String KEY_PREF_COMBINED = "sort_combined"; // See also @array/pref_sort_values
public static final String KEY_PREF_SEEDS = "sort_seeders"; // See also @array/pref_sort_values
public static final String KEY_PREF_LASTSORTGTZERO = "transdroid_interface_lastusedgtzero";
public static final String KEY_PREF_SWIPELABELS = "transdroid_interface_swipelabels";
public static final String KEY_PREF_NUMRESULTS = "transdroid_search_numresults";
public static final String KEY_PREF_SORT = "transdroid_search_sort";
public static final String KEY_PREF_UIREFRESH = "transdroid_interface_uirefresh";
public static final String KEY_PREF_ONLYDL = "transdroid_interface_onlydl";
public static final String KEY_PREF_HIDEREFRESH= "transdroid_interface_hiderefresh";
public static final String KEY_PREF_ASKREMOVE = "transdroid_interface_askremove";
public static final String KEY_PREF_ENABLEADS = "transdroid_interface_enableads";
public static final String KEY_PREF_RSSNAME = "transdroid_rss_name";
public static final String KEY_PREF_RSSURL = "transdroid_rss_url";
public static final String KEY_PREF_RSSAUTH = "transdroid_rss_needsauth";
public static final String KEY_PREF_RSSLASTNEW = "transdroid_rss_lastnew";
public static final String KEY_PREF_ENABLEALARM = "transdroid_alarm_enable";
public static final String KEY_PREF_ALARMINT = "transdroid_alarm_interval";
public static final String KEY_PREF_LASTUPDATE = "transdroid_alarm_lastupdatestats";
public static final String KEY_PREF_QUEUEDTOADD = "transdroid_alarm_queuedtoadd";
public static final String KEY_PREF_CHECKRSSFEEDS = "transdroid_alarm_checkrssfeeds";
public static final String KEY_PREF_ALARMPLAYSOUND = "transdroid_alarm_playsound";
public static final String KEY_PREF_ALARMSOUNDURI = "transdroid_alarm_sounduri";
public static final String KEY_PREF_ALARMVIBRATE = "transdroid_alarm_vibrate";
public static final String KEY_PREF_ALARMCOLOUR = "transdroid_alarm_colour";
public static final String KEY_PREF_ADWNOTIFY = "transdroid_alarm_adwnotify";
public static final String KEY_PREF_ADWONLYDL = "transdroid_alarm_adwonlydl";
public static final String KEY_PREF_CHECKUPDATES = "transdroid_alarm_checkupdates";
public static final String KEY_WIDGET_DAEMON = "transdroid_widget_daemon";
public static final String KEY_WIDGET_REFRESH = "transdroid_widget_refresh";
public static final String KEY_WIDGET_LAYOUT = "transdroid_widget_layout";
/**
* Determines the order number of the last used daemon settings object
* @param prefs The application's shared preferences
* @param allDaemons All available daemons settings
* @return The order number (0-based) of the server that was last used (or 0 if it doesn't exist any more)
*/
public static int readLastUsedDaemonOrderNumber(SharedPreferences prefs, List<DaemonSettings> allDaemons) {
// Get last used number
String prefLast = prefs.getString(KEY_PREF_LASTUSED, "");
int last = (prefLast == ""? 0: Integer.parseInt(prefLast));
if (last > allDaemons.size()) {
// The used daemon doesn't exist any more
return 0;
}
return last;
}
public static void removeDaemonSettings(SharedPreferences prefs, DaemonSettings toRemove) {
Editor editor = prefs.edit();
// Move all daemon settings 'up' 1 spot (by saving the preferences to an order id number 1 lower)
int id = (toRemove.getIdString() == ""? 0: Integer.parseInt(toRemove.getIdString()));
while (prefs.contains(KEY_PREF_ADDRESS + Integer.toString(id + 1))) {
// Copy the preferences
String fromId = Integer.toString(id + 1);
String toId = (id == 0? "": Integer.toString(id));
editor.putString(KEY_PREF_NAME + toId, prefs.getString(KEY_PREF_NAME + fromId, null));
editor.putString(KEY_PREF_DAEMON + toId, prefs.getString(KEY_PREF_DAEMON + fromId, null));
editor.putString(KEY_PREF_ADDRESS + toId, prefs.getString(KEY_PREF_ADDRESS + fromId, null));
editor.putString(KEY_PREF_PORT + toId, prefs.getString(KEY_PREF_PORT + fromId, null));
editor.putBoolean(KEY_PREF_SSL + toId, prefs.getBoolean(KEY_PREF_SSL + fromId, false));
editor.putBoolean(KEY_PREF_SSL_TRUST_ALL + toId, prefs.getBoolean(KEY_PREF_SSL_TRUST_ALL + fromId, false));
editor.putString(KEY_PREF_SSL_TRUST_KEY + toId, prefs.getString(KEY_PREF_SSL_TRUST_KEY + fromId, null));
editor.putString(KEY_PREF_FOLDER + toId, prefs.getString(KEY_PREF_FOLDER + fromId, null));
editor.putBoolean(KEY_PREF_AUTH + toId, prefs.getBoolean(KEY_PREF_AUTH + fromId, false));
editor.putString(KEY_PREF_USER + toId, prefs.getString(KEY_PREF_USER + fromId, null));
editor.putString(KEY_PREF_PASS + toId, prefs.getString(KEY_PREF_PASS + fromId, null));
editor.putString(KEY_PREF_EXTRAPASS + toId, prefs.getString(KEY_PREF_EXTRAPASS + fromId, null));
editor.putString(KEY_PREF_OS + toId, prefs.getString(KEY_PREF_OS + fromId, "type_windows"));
editor.putString(KEY_PREF_DOWNLOADDIR + toId, prefs.getString(KEY_PREF_DOWNLOADDIR + fromId, null));
editor.putString(KEY_PREF_FTPURL + toId, prefs.getString(KEY_PREF_FTPURL + fromId, null));
id++;
}
// Remove the last server preferences configuration
String delId = (id == 0? "": Integer.toString(id));
editor.remove(KEY_PREF_NAME + delId);
editor.remove(KEY_PREF_DAEMON + delId);
editor.remove(KEY_PREF_ADDRESS + delId);
editor.remove(KEY_PREF_PORT + delId);
editor.remove(KEY_PREF_SSL + delId);
editor.remove(KEY_PREF_FOLDER + delId);
editor.remove(KEY_PREF_AUTH + delId);
editor.remove(KEY_PREF_USER + delId);
editor.remove(KEY_PREF_PASS + delId);
editor.remove(KEY_PREF_EXTRAPASS + delId);
editor.remove(KEY_PREF_OS + delId);
editor.remove(KEY_PREF_DOWNLOADDIR + delId);
editor.remove(KEY_PREF_FTPURL + delId);
// If the last used daemon...
String lastUsed = prefs.getString(KEY_PREF_LASTUSED, "");
int lastUsedId = (lastUsed.equals("")? 0: Integer.parseInt(lastUsed));
int toRemoveId = (toRemove.getIdString() == ""? 0: Integer.parseInt(toRemove.getIdString()));
// ... was removed itself
if (lastUsed.equals(toRemove.getIdString())) {
// ... set the default to the very first configuration
// (this may also not exist any more, but this is handled by the UI)
editor.putString(KEY_PREF_LASTUSED, "");
// Else if is was move 'up' (now has an order number -1)
} else if (lastUsedId > toRemoveId) {
// ... update the last used setting appropriately
editor.putString(KEY_PREF_LASTUSED, (lastUsedId - 1 == 0? "": Integer.toString(lastUsedId - 1)));
}
editor.commit();
}
public static void removeXirvikSettings(SharedPreferences prefs, XirvikSettings toRemove) {
Editor editor = prefs.edit();
// Move all xirvik server settings 'up' 1 spot (by saving the preferences to an order id number 1 lower)
int id = (toRemove.getIdString() == ""? 0: Integer.parseInt(toRemove.getIdString()));
while (prefs.contains(KEY_PREF_XSERVER + Integer.toString(id + 1))) {
// Copy the preferences
String fromId = Integer.toString(id + 1);
String toId = (id == 0? "": Integer.toString(id));
editor.putString(KEY_PREF_XNAME + toId, prefs.getString(KEY_PREF_XNAME + fromId, null));
editor.putString(KEY_PREF_XTYPE + toId, prefs.getString(KEY_PREF_XTYPE + fromId, null));
editor.putString(KEY_PREF_XSERVER + toId, prefs.getString(KEY_PREF_XSERVER + fromId, null));
editor.putString(KEY_PREF_XFOLDER + toId, prefs.getString(KEY_PREF_XFOLDER + fromId, null));
editor.putString(KEY_PREF_XUSER + toId, prefs.getString(KEY_PREF_XUSER + fromId, null));
editor.putString(KEY_PREF_XPASS + toId, prefs.getString(KEY_PREF_XPASS + fromId, null));
editor.putString(KEY_PREF_XALARMFINISHED + toId, prefs.getString(KEY_PREF_XALARMFINISHED + fromId, null));
editor.putString(KEY_PREF_XALARMNEW + toId, prefs.getString(KEY_PREF_XALARMNEW + fromId, null));
id++;
}
// Remove the last server preferences configuration
String delId = (id == 0? "": Integer.toString(id));
editor.remove(KEY_PREF_XNAME + delId);
editor.remove(KEY_PREF_XTYPE + delId);
editor.remove(KEY_PREF_XSERVER + delId);
editor.remove(KEY_PREF_XUSER + delId);
editor.remove(KEY_PREF_XPASS + delId);
editor.remove(KEY_PREF_XALARMNEW + delId);
editor.remove(KEY_PREF_XALARMFINISHED + delId);
// If the last used daemon...
String lastUsed = prefs.getString(KEY_PREF_LASTUSED, "");
// no longer exists...
if (!prefs.contains(KEY_PREF_ADDRESS + lastUsed)) {
// Just reset the last used number
editor.putString(KEY_PREF_LASTUSED, "");
}
editor.commit();
}
public static void removeSeedM8Settings(SharedPreferences prefs, SeedM8Settings toRemove) {
Editor editor = prefs.edit();
// Move all SeedM8 server settings 'up' 1 spot (by saving the preferences to an order id number 1 lower)
int id = (toRemove.getIdString() == ""? 0: Integer.parseInt(toRemove.getIdString()));
while (prefs.contains(KEY_PREF_8SERVER + Integer.toString(id + 1))) {
// Copy the preferences
String fromId = Integer.toString(id + 1);
String toId = (id == 0? "": Integer.toString(id));
editor.putString(KEY_PREF_8NAME + toId, prefs.getString(KEY_PREF_8NAME + fromId, null));
editor.putString(KEY_PREF_8SERVER+ toId, prefs.getString(KEY_PREF_XSERVER + fromId, null));
editor.putString(KEY_PREF_8USER + toId, prefs.getString(KEY_PREF_XUSER + fromId, null));
editor.putString(KEY_PREF_8DPASS + toId, prefs.getString(KEY_PREF_8DPASS + fromId, null));
editor.putString(KEY_PREF_8DPORT + toId, prefs.getString(KEY_PREF_8DPORT + fromId, null));
editor.putString(KEY_PREF_8TPASS + toId, prefs.getString(KEY_PREF_8TPASS + fromId, null));
editor.putString(KEY_PREF_8TPORT + toId, prefs.getString(KEY_PREF_8TPORT + fromId, null));
editor.putString(KEY_PREF_8RPASS + toId, prefs.getString(KEY_PREF_8RPASS + fromId, null));
editor.putString(KEY_PREF_8SPASS + toId, prefs.getString(KEY_PREF_8SPASS + fromId, null));
editor.putString(KEY_PREF_8ALARMFINISHED + toId, prefs.getString(KEY_PREF_8ALARMFINISHED + fromId, null));
editor.putString(KEY_PREF_8ALARMNEW + toId, prefs.getString(KEY_PREF_8ALARMNEW + fromId, null));
id++;
}
// Remove the last server preferences configuration
String delId = (id == 0? "": Integer.toString(id));
editor.remove(KEY_PREF_8NAME + delId);
editor.remove(KEY_PREF_8SERVER + delId);
editor.remove(KEY_PREF_8USER + delId);
editor.remove(KEY_PREF_8DPASS + delId);
editor.remove(KEY_PREF_8DPORT + delId);
editor.remove(KEY_PREF_8TPASS + delId);
editor.remove(KEY_PREF_8TPORT + delId);
editor.remove(KEY_PREF_8RPASS + delId);
editor.remove(KEY_PREF_8SPASS + delId);
editor.remove(KEY_PREF_8ALARMNEW + delId);
editor.remove(KEY_PREF_8ALARMFINISHED + delId);
// If the last used daemon...
String lastUsed = prefs.getString(KEY_PREF_LASTUSED, "");
// no longer exists...
if (!prefs.contains(KEY_PREF_ADDRESS + lastUsed)) {
// Just reset the last used number
editor.putString(KEY_PREF_LASTUSED, "");
}
editor.commit();
}
public static void removeSeedstuffSettings(SharedPreferences prefs, SeedstuffSettings toRemove) {
Editor editor = prefs.edit();
// Move all seedstuff server settings 'up' 1 spot (by saving the preferences to an order id number 1 lower)
int id = (toRemove.getIdString() == ""? 0: Integer.parseInt(toRemove.getIdString()));
while (prefs.contains(KEY_PREF_SUSER + Integer.toString(id + 1))) {
// Copy the preferences
String fromId = Integer.toString(id + 1);
String toId = (id == 0? "": Integer.toString(id));
editor.putString(KEY_PREF_SNAME + toId, prefs.getString(KEY_PREF_SNAME + fromId, null));
editor.putString(KEY_PREF_SSERVER + toId, prefs.getString(KEY_PREF_SSERVER + fromId, null));
editor.putString(KEY_PREF_SUSER + toId, prefs.getString(KEY_PREF_SUSER + fromId, null));
editor.putString(KEY_PREF_SPASS + toId, prefs.getString(KEY_PREF_SPASS + fromId, null));
editor.putString(KEY_PREF_SALARMFINISHED + toId, prefs.getString(KEY_PREF_SALARMFINISHED + fromId, null));
editor.putString(KEY_PREF_SALARMNEW + toId, prefs.getString(KEY_PREF_SALARMNEW + fromId, null));
id++;
}
// Remove the last server preferences configuration
String delId = (id == 0? "": Integer.toString(id));
editor.remove(KEY_PREF_SNAME + delId);
editor.remove(KEY_PREF_SSERVER + delId);
editor.remove(KEY_PREF_SUSER + delId);
editor.remove(KEY_PREF_SPASS + delId);
editor.remove(KEY_PREF_SALARMNEW + delId);
editor.remove(KEY_PREF_SALARMFINISHED + delId);
// If the last used daemon...
String lastUsed = prefs.getString(KEY_PREF_LASTUSED, "");
// no longer exists...
if (!prefs.contains(KEY_PREF_ADDRESS + lastUsed)) {
// Just reset the last used number
editor.putString(KEY_PREF_LASTUSED, "");
}
editor.commit();
}
public static void removeSiteSettings(SharedPreferences prefs, SiteSettings toRemove) {
Editor editor = prefs.edit();
// Move all site settings 'up' 1 spot (by saving the preferences to an order id number 1 lower)
int id = Integer.parseInt(toRemove.getKey());
while (prefs.contains(KEY_PREF_WEBURL + Integer.toString(id + 1))) {
// Copy the preferences
String fromId = Integer.toString(id + 1);
String toId = Integer.toString(id);
editor.putString(KEY_PREF_WEBSITE + toId, prefs.getString(KEY_PREF_WEBSITE + fromId, null));
editor.putString(KEY_PREF_WEBURL + toId, prefs.getString(KEY_PREF_WEBURL + fromId, null));
id++;
}
// Remove the last preferences configuration
String delId = Integer.toString(id);
editor.remove(KEY_PREF_WEBSITE + delId);
editor.remove(KEY_PREF_WEBURL + delId);
// If the default search site...
SiteSettings defaultSite = readDefaultSearchSiteSettings(prefs);
// ... is a web search site
if (defaultSite.isWebSearch()) {
int toRemoveId = Integer.parseInt(toRemove.getKey());
int defaultSiteId = Integer.parseInt(defaultSite.getKey());
// ... and was removed itself
if (defaultSite.getKey().equals(toRemove.getKey())) {
// ... set the default back to the default default :)
editor.putString(KEY_PREF_SITE, KEY_PREF_DEF_SITE);
// else if it was moved 'up' (now has an order number -1)
} else if (defaultSiteId > toRemoveId) {
// ... update the default site appropriately
editor.putString(KEY_PREF_SITE, Integer.toString(defaultSiteId - 1));
}
}
editor.commit();
}
public static void removeRssFeedSettings(SharedPreferences prefs, RssFeedSettings toRemove) {
Editor editor = prefs.edit();
// Move all feed settings 'up' 1 spot (by saving the preferences to an order id number 1 lower)
int id = Integer.parseInt(toRemove.getKey());
while (prefs.contains(KEY_PREF_RSSURL + Integer.toString(id + 1))) {
// Copy the preferences
String fromId = Integer.toString(id + 1);
String toId = Integer.toString(id);
editor.putString(KEY_PREF_RSSNAME + toId, prefs.getString(KEY_PREF_RSSNAME + fromId, null));
editor.putString(KEY_PREF_RSSURL + toId, prefs.getString(KEY_PREF_RSSURL + fromId, null));
editor.putBoolean(KEY_PREF_RSSAUTH + toId, prefs.getBoolean(KEY_PREF_RSSAUTH + fromId, false));
editor.putString(KEY_PREF_RSSLASTNEW + toId, prefs.getString(KEY_PREF_RSSLASTNEW + fromId, null));
id++;
}
// Remove the last preferences configuration
String delId = Integer.toString(id);
editor.remove(KEY_PREF_RSSNAME + delId);
editor.remove(KEY_PREF_RSSURL + delId);
editor.remove(KEY_PREF_RSSAUTH + delId);
editor.remove(KEY_PREF_RSSLASTNEW + delId);
editor.commit();
}
public static void moveRssFeedSettings(SharedPreferences prefs, RssFeedSettings toMove, boolean moveUp) {
Editor editor = prefs.edit();
// Which feeds to switch position of (bounds are NOT checked)
int from = Integer.parseInt(toMove.getKey());
int to;
if (moveUp) {
to = from - 1;
} else {
to = from + 1;
}
// Switch their settings
String fromName = prefs.getString(KEY_PREF_RSSNAME + from, null);
String fromUrl = prefs.getString(KEY_PREF_RSSURL + from, null);
boolean fromAuth = prefs.getBoolean(KEY_PREF_RSSAUTH + from, false);
String fromLast = prefs.getString(KEY_PREF_RSSLASTNEW + from, null);
editor.putString(KEY_PREF_RSSNAME + from, prefs.getString(KEY_PREF_RSSNAME + to, null));
editor.putString(KEY_PREF_RSSURL + from, prefs.getString(KEY_PREF_RSSURL + to, null));
editor.putBoolean(KEY_PREF_RSSAUTH + from, prefs.getBoolean(KEY_PREF_RSSAUTH + to, false));
editor.putString(KEY_PREF_RSSLASTNEW + from, prefs.getString(KEY_PREF_RSSLASTNEW + to, null));
editor.putString(KEY_PREF_RSSNAME + to, fromName);
editor.putString(KEY_PREF_RSSURL + to, fromUrl);
editor.putBoolean(KEY_PREF_RSSAUTH + to, fromAuth);
editor.putString(KEY_PREF_RSSLASTNEW + to, fromLast);
editor.commit();
}
/**
* Build a list of xirvik server setting objects, available in the stored preferences
* @param prefs The application's shared preferences
* @return A list of all xirvik server configurations available
*/
public static List<XirvikSettings> readAllXirvikSettings(SharedPreferences prefs) {
// Build a list of xirvik server setting objects, available in the stored preferences
List<XirvikSettings> xservers = new ArrayList<XirvikSettings>();
int i = 0;
String nextName = KEY_PREF_XSERVER;
while (prefs.contains(nextName)) {
// The first server is stored without number, subsequent ones have an order number after the regular pref key
String postfix = (i == 0? "": Integer.toString(i));
// Add an entry for this server
xservers.add(readXirvikSettings(prefs, postfix));
// Search for more
i++;
nextName = KEY_PREF_XSERVER + Integer.toString(i);
}
return xservers;
}
/**
* Build a list of seedm8 server setting objects, available in the stored preferences
* @param prefs The application's shared preferences
* @return A list of all seedm8 server configurations available
*/
public static List<SeedM8Settings> readAllSeedM8Settings(SharedPreferences prefs) {
// Build a list of seedm8 server setting objects, available in the stored preferences
List<SeedM8Settings> s8servers = new ArrayList<SeedM8Settings>();
int i = 0;
String nextName = KEY_PREF_8SERVER;
while (prefs.contains(nextName)) {
// The first server is stored without number, subsequent ones have an order number after the regular pref key
String postfix = (i == 0? "": Integer.toString(i));
// Add an entry for this server
s8servers.add(readSeedM8Settings(prefs, postfix));
// Search for more
i++;
nextName = KEY_PREF_8SERVER + Integer.toString(i);
}
return s8servers;
}
/**
* Build a list of seedstuff server setting objects, available in the stored preferences
* @param prefs The application's shared preferences
* @return A list of all seedstuff server configurations available
*/
public static List<SeedstuffSettings> readAllSeedstuffSettings(SharedPreferences prefs) {
// Build a list of seedstuff server setting objects, available in the stored preferences
List<SeedstuffSettings> sservers = new ArrayList<SeedstuffSettings>();
int i = 0;
String nextName = KEY_PREF_SUSER;
while (prefs.contains(nextName)) {
// The first server is stored without number, subsequent ones have an order number after the regular pref key
String postfix = (i == 0? "": Integer.toString(i));
// Add an entry for this server
sservers.add(readSeedstuffSettings(prefs, postfix));
// Search for more
i++;
nextName = KEY_PREF_SUSER + Integer.toString(i);
}
return sservers;
}
/**
* Build a list of server setting objects, available in the stored preferences
* @param prefs The application's shared preferences
* @return A list of all daemon configurations available
*/
public static List<DaemonSettings> readAllNormalDaemonSettings(SharedPreferences prefs) {
// Build a list of server setting objects, available in the stored preferences
List<DaemonSettings> daemons = new ArrayList<DaemonSettings>();
int i = 0;
String nextName = KEY_PREF_ADDRESS;
while (prefs.contains(nextName)) {
// The first server is stored without number, subsequent ones have an order number after the regular pref key
String postfix = (i == 0? "": Integer.toString(i));
// Add an entry for this server
daemons.add(readDaemonSettings(prefs, postfix));
// Search for more
i++;
nextName = KEY_PREF_ADDRESS + Integer.toString(i);
}
return daemons;
}
public static List<DaemonSettings> readAllDaemonSettings(SharedPreferences prefs) {
// Build a list of all 'normal' (manual) and all xirvik daemons
List<DaemonSettings> daemons = readAllNormalDaemonSettings(prefs);
int max = -1;
if (daemons.size() > 0) {
String maxId = daemons.get(daemons.size() - 1).getIdString();
max = maxId.equals("")? 0: Integer.parseInt(maxId);
}
for (XirvikSettings xirvik : readAllXirvikSettings(prefs)) {
daemons.addAll(xirvik.createDaemonSettings(max + 1));
}
if (daemons.size() > 0) {
String maxId = daemons.get(daemons.size() - 1).getIdString();
max = maxId.equals("")? 0: Integer.parseInt(maxId);
}
for (SeedM8Settings seedm8 : readAllSeedM8Settings(prefs)) {
daemons.addAll(seedm8.createDaemonSettings(max + 1));
}
for (SeedstuffSettings seedstuff : readAllSeedstuffSettings(prefs)) {
daemons.addAll(seedstuff.createDaemonSettings(max + 1));
}
return daemons;
}
/**
* Build a list of site setting objects; in-app ones and those available in the stored preferences
* @param prefs The application's shared preferences
* @return A list of all site configurations available
*/
public static List<SiteSettings> readAllSiteSettings(SharedPreferences prefs) {
// Build a list of in-app sites
List<SiteSettings> sites = getSupportedSiteSettings();
// Add site setting objects for web search sites, available in the stored preferences
sites.addAll(readAllWebSearchSiteSettings(prefs));
return sites;
}
/**
* Returns a list of search site settings for supported torrent search sites
* @return An ordered list of site settings for all available adapters
*/
public static List<SiteSettings> getSupportedSiteSettings() {
List<SiteSettings> settings = new ArrayList<SiteSettings>();
settings.add(new SiteSettings("site_bitsnoop", "BitSnoop"));
settings.add(new SiteSettings("site_extratorrent", "ExtraTorrent"));
settings.add(new SiteSettings("site_isohunt", "isoHunt"));
settings.add(new SiteSettings("site_kickasstorrents", "KickassTorrents"));
settings.add(new SiteSettings("site_limetorrents", "LimeTorrents"));
settings.add(new SiteSettings("site_mininova", "Mininova"));
settings.add(new SiteSettings("site_monova", "Monova"));
settings.add(new SiteSettings("site_thepiratebay", "The Pirate Bay"));
settings.add(new SiteSettings("site_thepiratebaymirror", "The Pirate Bay (Mirror)"));
settings.add(new SiteSettings("site_torrentdownloads", "Torrent Downloads"));
settings.add(new SiteSettings("site_torrentreactor", "Torrent Reactor"));
settings.add(new SiteSettings("site_vertor", "Vertor"));
return settings;
}
/**
* Returns the unique key to use in search request to the content provider
* from the unique key as use din Transdroid's settings (for compatibility)
* @param preferencesKey The Transdroid preferences key, f.e. 'iso_mininova'
* @return The Transdroid Torrent Search site key, f.e. 'Mininova'
*/
public static String getCursorKeyForPreferencesKey(String preferencesKey) {
if (preferencesKey.equals("site_bitsnoop")) {
return "BitSnoop";
} else if (preferencesKey.equals("site_extratorrent")) {
return "ExtraTorrent";
} else if (preferencesKey.equals("site_isohunt")) {
return "Isohunt";
} else if (preferencesKey.equals("site_kickasstorrents")) {
return "KickassTorents";
} else if (preferencesKey.equals("site_limetorrents")) {
return "LimeTorrents";
} else if (preferencesKey.equals("site_mininova")) {
return "Mininova";
} else if (preferencesKey.equals("site_monova")) {
return "Monova";
} else if (preferencesKey.equals("site_thepiratebay")) {
return "ThePirateBay";
} else if (preferencesKey.equals("site_thepiratebaymirror")) {
return "ThePirateBayMirror";
} else if (preferencesKey.equals("site_torrentdownloads")) {
return "TorrentDownloads";
} else if (preferencesKey.equals("site_torrentreactor")) {
return "TorrentReactor";
} else if (preferencesKey.equals("site_vertor")) {
return "Vertor";
}
return null;
}
public static SiteSettings getSupportedSiteSetting(String preferencesKey) {
if (preferencesKey.equals("site_bitsnoop")) {
return new SiteSettings(preferencesKey, "BitSnoop");
} else if (preferencesKey.equals("site_extratorrent")) {
return new SiteSettings(preferencesKey, "ExtraTorrent");
} else if (preferencesKey.equals("site_isohunt")) {
return new SiteSettings(preferencesKey, "Isohunt");
} else if (preferencesKey.equals("site_kickasstorrents")) {
return new SiteSettings(preferencesKey, "KickassTorents");
} else if (preferencesKey.equals("site_limetorrents")) {
return new SiteSettings(preferencesKey, "LimeTorrents");
} else if (preferencesKey.equals("site_mininova")) {
return new SiteSettings(preferencesKey, "Mininova");
} else if (preferencesKey.equals("site_monova")) {
return new SiteSettings(preferencesKey, "Monova");
} else if (preferencesKey.equals("site_thepiratebay")) {
return new SiteSettings(preferencesKey, "ThePirateBay");
} else if (preferencesKey.equals("site_thepiratebaymirror")) {
return new SiteSettings(preferencesKey, "ThePirateBayMirror");
} else if (preferencesKey.equals("site_torrentdownloads")) {
return new SiteSettings(preferencesKey, "TorrentDownloads");
} else if (preferencesKey.equals("site_torrentreactor")) {
return new SiteSettings(preferencesKey, "TorrentReactor");
} else if (preferencesKey.equals("site_vertor")) {
return new SiteSettings(preferencesKey, "Vertor");
}
return null;
}
public static SiteSettings readDefaultSearchSiteSettings(SharedPreferences prefs) {
String prefName = prefs.getString(KEY_PREF_SITE, KEY_PREF_DEF_SITE);
// In-app search?
SiteSettings inapp = getSupportedSiteSetting(prefName);
if (inapp != null) {
return inapp;
}
// Web-based search
if (!prefs.contains(KEY_PREF_WEBURL + prefName)) {
// The set default doesn't exists any more: return the default default :) search
return getSupportedSiteSetting(KEY_PREF_DEF_SITE);
}
return readSiteSettings(prefs, prefName);
}
/**
* Build a list of web-based search sites
* @param prefs The application's shared preferences
* @return A list of all web search configurations available
*/
public static List<SiteSettings> readAllWebSearchSiteSettings(SharedPreferences prefs) {
List<SiteSettings> sites = new ArrayList<SiteSettings>();
// Add site setting objects for web search sites, available in the stored preferences
int i = 0;
String nextName = KEY_PREF_WEBURL + Integer.toString(i);
while (prefs.contains(nextName)) {
// Stored sites have a zero-based order number
String postfix = Integer.toString(i);
// Add an entry for this server
sites.add(readSiteSettings(prefs, postfix));
// Search for more
i++;
nextName = KEY_PREF_WEBURL + Integer.toString(i);
}
return sites;
}
/**
* Build a list of rss feed setting objects as available in the stored preferences
* @param prefs The application's shared preferences
* @return A list of all feeds available
*/
public static List<RssFeedSettings> readAllRssFeedSettings(SharedPreferences prefs) {
// Build a list of in-app sites
List<RssFeedSettings> feeds = new ArrayList<RssFeedSettings>();
// Add feed setting objects available in the stored preferences
int i = 0;
String nextName = KEY_PREF_RSSURL + Integer.toString(i);
while (prefs.contains(nextName)) {
// Stored sites have a zero-based order number
String postfix = Integer.toString(i);
// Add an entry for this server
feeds.add(readRssFeedSettings(prefs, postfix));
// Search for more
i++;
nextName = KEY_PREF_RSSURL + Integer.toString(i);
}
return feeds;
}
/**
* Read the settings of the last used daemon configuration
* @param prefs The preferences object to retrieve the settings from
* @param allDaemons All available daemons settings
* @return The daemon settings of the last used configuration
*/
public static DaemonSettings readLastUsedDaemonSettings(SharedPreferences prefs, List<DaemonSettings> allDaemons) {
if (allDaemons == null || allDaemons.size() == 0) {
return null;
}
int last = readLastUsedDaemonOrderNumber(prefs, allDaemons);
return allDaemons.get(last);
}
/**
* Store the new default search site, so all 'traffic' will be directed here
* @param context The application context to get the preferences from
* @param siteKey The unique key of the search site that needs to be made default
*/
public static void storeLastUsedSearchSiteSettings(Context context, String siteKey) {
Editor edit = PreferenceManager.getDefaultSharedPreferences(context).edit();
edit.putString(KEY_PREF_SITE, siteKey);
edit.commit();
}
/**
* Store the last used daemon settings, so all 'traffic' will be directed here
* @param context The application context to get the preferences from
* @param daemonOrderNumber The order number of the last used daemon settings object
*/
public static void storeLastUsedDaemonSettings(Context context, int daemonOrderNumber) {
Editor edit = PreferenceManager.getDefaultSharedPreferences(context).edit();
edit.putString(KEY_PREF_LASTUSED, (daemonOrderNumber == 0? "": Integer.toString(daemonOrderNumber)));
edit.commit();
}
private static XirvikSettings readXirvikSettings(SharedPreferences prefs, String postfix) {
// Read saved preferences
String prefType = prefs.getString(KEY_PREF_XTYPE + postfix, null);
// Return daemon settings
return new XirvikSettings(
prefs.getString(KEY_PREF_XNAME + postfix, null),
XirvikServerType.fromCode(prefType),
prefs.getString(KEY_PREF_XSERVER + postfix, null),
prefs.getString(KEY_PREF_XFOLDER + postfix, XirvikSettings.RTORRENT_FOLDER),
prefs.getString(KEY_PREF_XUSER + postfix, null),
prefs.getString(KEY_PREF_XPASS + postfix, null),
prefs.getBoolean(KEY_PREF_XALARMFINISHED + postfix, true),
prefs.getBoolean(KEY_PREF_XALARMNEW + postfix, false),
postfix);
}
private static SeedM8Settings readSeedM8Settings(SharedPreferences prefs, String postfix) {
// Read saved preferences
String prefDPort = prefs.getString(KEY_PREF_8DPORT + postfix, null);
String prefTPort = prefs.getString(KEY_PREF_8TPORT + postfix, null);
// Test if ports are set
int prefDPortI = Daemon.getDefaultPortNumber(Daemon.Deluge, false);
try {
int dportI = Integer.parseInt(prefDPort);
if (dportI > 0) {
prefDPortI = dportI;
}
} catch (NumberFormatException e) { }
int prefTPortI = Daemon.getDefaultPortNumber(Daemon.Transmission, false);
try {
int tportI = Integer.parseInt(prefTPort);
if (tportI > 0) {
prefTPortI = tportI;
}
} catch (NumberFormatException e) { }
// Return daemon settings
return new SeedM8Settings(
prefs.getString(KEY_PREF_8NAME + postfix, null),
prefs.getString(KEY_PREF_8SERVER + postfix, null),
prefs.getString(KEY_PREF_8USER + postfix, null),
prefDPortI,
prefs.getString(KEY_PREF_8DPASS + postfix, null),
prefTPortI,
prefs.getString(KEY_PREF_8TPASS + postfix, null),
prefs.getString(KEY_PREF_8RPASS + postfix, null),
prefs.getString(KEY_PREF_8SPASS + postfix, null),
prefs.getBoolean(KEY_PREF_XALARMFINISHED + postfix, true),
prefs.getBoolean(KEY_PREF_XALARMNEW + postfix, false),
postfix);
}
private static SeedstuffSettings readSeedstuffSettings(SharedPreferences prefs, String postfix) {
// Return daemon settings
return new SeedstuffSettings(
prefs.getString(KEY_PREF_SNAME + postfix, null),
prefs.getString(KEY_PREF_SSERVER + postfix, null),
prefs.getString(KEY_PREF_SUSER + postfix, null),
prefs.getString(KEY_PREF_SPASS + postfix, null),
prefs.getBoolean(KEY_PREF_SALARMFINISHED + postfix, true),
prefs.getBoolean(KEY_PREF_SALARMNEW + postfix, false),
postfix);
}
private static DaemonSettings readDaemonSettings(SharedPreferences prefs, String postfix) {
// Read saved preferences
String prefName = prefs.getString(KEY_PREF_NAME + postfix, null);
Daemon prefDaemon = Daemon.fromCode(prefs.getString(KEY_PREF_DAEMON + postfix, null));
String prefAddress = prefs.getString(KEY_PREF_ADDRESS + postfix, null);
String prefFolder = prefs.getString(KEY_PREF_FOLDER + postfix, "");
String prefPort = prefs.getString(KEY_PREF_PORT + postfix, null);
boolean prefSsl = prefs.getBoolean(KEY_PREF_SSL + postfix, false);
String prefTimeout = prefs.getString(KEY_PREF_TIMEOUT + postfix, null);
// Parse port number
int prefPortI = Daemon.getDefaultPortNumber(prefDaemon, prefSsl);
try {
int portI = Integer.parseInt(prefPort);
if (portI > 0) {
prefPortI = portI;
}
} catch (NumberFormatException e) { }
// Parse timeout time
int prefTimeoutI = HttpHelper.DEFAULT_CONNECTION_TIMEOUT;
try {
int timeoutI = Integer.parseInt(prefTimeout);
if (timeoutI > 0) {
prefTimeoutI = timeoutI;
}
} catch (NumberFormatException e) { }
// Return daemon settings
return new DaemonSettings(
prefName,
prefDaemon,
prefAddress.trim().replace("\t", ""),
prefPortI,
prefSsl,
prefs.getBoolean(KEY_PREF_SSL_TRUST_ALL + postfix, false),
prefs.getString(KEY_PREF_SSL_TRUST_KEY + postfix, null),
prefFolder,
prefs.getBoolean(KEY_PREF_AUTH + postfix, false),
prefs.getString(KEY_PREF_USER + postfix, null),
prefs.getString(KEY_PREF_PASS + postfix, null),
prefs.getString(KEY_PREF_EXTRAPASS + postfix, null),
OS.fromCode(prefs.getString(KEY_PREF_OS + postfix, "type_windows")),
prefs.getString(KEY_PREF_DOWNLOADDIR + postfix, null),
prefs.getString(KEY_PREF_FTPURL + postfix, null),
prefs.getString(KEY_PREF_PASS + postfix, null),
prefTimeoutI,
prefs.getBoolean(KEY_PREF_ALARMFINISHED + postfix, true),
prefs.getBoolean(KEY_PREF_ALARMNEW + postfix, false),
postfix,
false);
}
private static SiteSettings readSiteSettings(SharedPreferences prefs, String postfix) {
// Read saved preferences
String prefName = prefs.getString(KEY_PREF_WEBSITE + postfix, null);
String prefUrl = prefs.getString(KEY_PREF_WEBURL + postfix, null);
// Return site settings
return new SiteSettings(postfix, prefName, prefUrl);
}
public static RssFeedSettings readRssFeedSettings(SharedPreferences prefs, String postfix) {
// Read saved preferences
String prefName = prefs.getString(KEY_PREF_RSSNAME + postfix, null);
String prefUrl = prefs.getString(KEY_PREF_RSSURL + postfix, null);
boolean prefNeedsAuth = prefs.getBoolean(KEY_PREF_RSSAUTH + postfix, false);
String prefLastNew = prefs.getString(KEY_PREF_RSSLASTNEW + postfix, null);
// Return rss feed settings
return new RssFeedSettings(postfix, prefName, prefUrl, prefNeedsAuth, prefLastNew);
}
/**
* Read the global settings for searches
* @param prefs The preferences object to retrieve the settings from
* @return The current search settings
*/
public static SearchSettings readSearchSettings(SharedPreferences prefs) {
// Read saved preferences
String prefNumResults = prefs.getString(KEY_PREF_NUMRESULTS, "25");
String prefSort = prefs.getString(KEY_PREF_SORT, KEY_PREF_SEEDS);
// Return search settings
return new SearchSettings(Integer.parseInt(prefNumResults), !prefSort.equals(KEY_PREF_COMBINED));
}
/**
* Read global the interface settings
* @param prefs The preferences object to retrieve the settings from
* @return The current interface settings
*/
public static InterfaceSettings readInterfaceSettings(SharedPreferences prefs) {
// Read saved preferences
String prefUIRefresh = prefs.getString(KEY_PREF_UIREFRESH, "-1");
// Return interface settings
return new InterfaceSettings(
prefs.getBoolean(KEY_PREF_SWIPELABELS, false),
Integer.parseInt(prefUIRefresh),
prefs.getBoolean(KEY_PREF_ONLYDL, false),
prefs.getBoolean(KEY_PREF_HIDEREFRESH, false),
prefs.getBoolean(KEY_PREF_ASKREMOVE, true),
prefs.getBoolean(KEY_PREF_ENABLEADS, true));
}
/**
* Read the global alarm settings
* @param prefs The preferences object to retrieve the settings from
* @return The current alarm settings
*/
public static AlarmSettings readAlarmSettings(SharedPreferences prefs) {
// Read saved preferences
String prefAlarmInt = prefs.getString(KEY_PREF_ALARMINT, "600000");
// Return alarm settings
return new AlarmSettings(
prefs.getBoolean(KEY_PREF_ENABLEALARM, false),
Integer.parseInt(prefAlarmInt),
prefs.getBoolean(KEY_PREF_CHECKRSSFEEDS, false),
prefs.getBoolean(KEY_PREF_ALARMPLAYSOUND, false),
prefs.getString(KEY_PREF_ALARMSOUNDURI, null),
prefs.getBoolean(KEY_PREF_ALARMVIBRATE, false),
prefs.getInt(KEY_PREF_ALARMCOLOUR, 0xff7dbb21),
prefs.getBoolean(KEY_PREF_ADWNOTIFY, false),
prefs.getBoolean(KEY_PREF_ADWONLYDL, false),
prefs.getBoolean(KEY_PREF_CHECKUPDATES, true));
}
/**
* Retrieve a structure containing the stats of the last alarm service update
* @param prefs The preferences object to retrieve the stats from
* @return For each daemon (identified by code) a list of torrent ids with an indication whether they were finished
*/
public static Map<String, ArrayList<Pair<String, Boolean>>> readLastAlarmStatsUpdate(SharedPreferences prefs) {
// Get the last update stats from the user preferences
String lastUpdate = prefs.getString(KEY_PREF_LASTUPDATE, null);
if (lastUpdate == null || lastUpdate.equals("")) {
return null;
}
// Explode this list of torrent stats
try {
HashMap<String, ArrayList<Pair<String, Boolean>>> last = new HashMap<String, ArrayList<Pair<String, Boolean>>>();
if (!lastUpdate.equals("")) {
String[] daemons = lastUpdate.split("\\|");
for (String daemon : daemons) {
if (!daemon.equals("")) {
String[] daemonData = daemon.split(";");
String daemonCode = "";
if (daemonData.length != 0) {
daemonCode = daemonData[0];
}
ArrayList<Pair<String, Boolean>> torentList = new ArrayList<Pair<String, Boolean>>();
if (daemonData.length > 1) {
String[] torrents = daemonData[1].split(":");
for (String torrent : torrents) {
if (!torrent.equals("")) {
// Add this torrent
String[] stats = torrent.split(",");
torentList.add(new Pair<String, Boolean>(stats[0], Boolean.parseBoolean(stats[1])));
}
}
}
// Add this torrent (stats)
last.put(daemonCode, torentList);
}
}
}
return last;
} catch (Exception e) {
// A malformed string was present in the user preferences
return null;
}
}
/**
* Store the torrent stats from a recent alarm service update
* @param prefs The preferences object to retrieve the stats from
* @param thisUpdate The newly retrieved list of running torrents on the server
*/
public static void storeLastAlarmStatsUpdate(SharedPreferences prefs, HashMap<String, ArrayList<Pair<String, Boolean>>> thisUpdate) {
StringBuilder lastUpdate = new StringBuilder();
// For each daemon, store its code and torrents list
int id = 0;
for (Entry<String, ArrayList<Pair<String, Boolean>>> daemon : thisUpdate.entrySet()) {
if (id > 0) {
lastUpdate.append("|");
}
lastUpdate.append(daemon.getKey());
lastUpdate.append(";");
int it = 0;
for (Pair<String, Boolean> torrent : daemon.getValue()) {
if (it > 0) {
lastUpdate.append(":");
}
lastUpdate.append(torrent.first);
lastUpdate.append(",");
lastUpdate.append(torrent.second.toString());
it++;
}
id++;
}
Editor editor = prefs.edit();
editor.putString(KEY_PREF_LASTUPDATE, lastUpdate.toString());
editor.commit();
}
/**
* Reads the list of torrents that are queued to be added later and clears the queue immediately
* @param prefs The preferences object to retrieve the stats from
* @return The list of torrent uris as strings
*/
public static List<Pair<String, String>> readAndClearTorrentAddQueue(SharedPreferences prefs) {
// Get the list or torrents stored to add later from the user preferences
String queue = prefs.getString(KEY_PREF_QUEUEDTOADD, "");
// Clear queue
if (!queue.equals("")) {
Editor editor = prefs.edit();
editor.putString(KEY_PREF_QUEUEDTOADD, "");
editor.commit();
}
// Parse and return as list
try {
ArrayList<Pair<String, String>> list = new ArrayList<Pair<String, String>>();
if (queue.equals("")) {
return list;
}
for (String torrent : queue.split("\\|")) {
String[] torrentData = torrent.split(";");
list.add(new Pair<String, String>(torrentData[0], torrentData[1]));
}
return list;
} catch (Exception e) {
// A malformed string was present in the user preferences
return new ArrayList<Pair<String, String>>();
}
}
/**
* Add a torrent uri to the list of torrents to add later
* @param prefs The preferences object to retrieve the stats from
* @param daemonStringId The string ID for the daemon to add the torrent to
* @param torrentToStore The uri of the torrent to add as a string
*/
public static void addToTorrentAddQueue(SharedPreferences prefs, String daemonStringId, String torrentToStore) {
addToTorrentAddQueue(prefs, daemonStringId + ";" + torrentToStore);
}
/**
* Add a torrent uri to the list of torrents to add later
* @param prefs The preferences object to retrieve the stats from
* @param daemonStringId The string ID for the daemon to add the torrent to
* @param torrentData ;-combined daemon id strings and torrent uris
*/
public static void addToTorrentAddQueue(SharedPreferences prefs, String torrentData) {
// Add the given torrent uri to the existing queue
String queue = prefs.getString(KEY_PREF_QUEUEDTOADD, "");
if (!queue.equals("")) {
queue += "|";
}
queue += torrentData;
// Store it
Editor editor = prefs.edit();
editor.putString(KEY_PREF_QUEUEDTOADD, queue);
editor.commit();
}
/**
* Indicates whether this torrent uri points to a local file
* @param torrentUri The raw torrent uri string
* @return False it it seems like a web uri (starting with http or magnet); true otherwise
*/
public static boolean isQueuedTorrentToAddALocalFile(String torrentUri) {
return torrentUri != null && !(torrentUri.startsWith(HttpHelper.SCHEME_HTTP) || torrentUri.startsWith(HttpHelper.SCHEME_MAGNET));
}
/**
* Indicates whether this torrent uri points to a magnet url
* @param torrentUri The raw torrent uri string
* @return True it it seems like a magnet link (starting with magnet); true otherwise
*/
public static boolean isQueuedTorrentToAddAMagnetUrl(String torrentUri) {
return torrentUri != null && torrentUri.startsWith(HttpHelper.SCHEME_MAGNET);
}
public static CharSequence parseArrayEntryFromValue(Context context, int entryArray, int valueArray, String findValue) {
CharSequence[] values = context.getResources().getTextArray(valueArray);
CharSequence[] entries = context.getResources().getTextArray(entryArray);
// Check array length
if (values.length != entries.length) {
throw new InvalidParameterException("Arrays need to be of equal length.");
}
int i = 0;
for (CharSequence value : values) {
if (value.equals(findValue)) {
return entries[i];
}
i++;
}
// Not found
return null;
}
/**
* Read the global settings for searches
* @param prefs The preferences object to retrieve the settings from
* @param widgetId The id of the widget for which to get the settings
* @return The current search settings
*/
public static WidgetSettings readWidgetSettings(SharedPreferences prefs, int widgetID, List<DaemonSettings> allDaemons) {
// Read and parse daemon
String prefDaemon = prefs.getString(KEY_WIDGET_DAEMON + widgetID, null);
DaemonSettings daemonSettings;
int daemonId = (prefDaemon == null || prefDaemon == ""? 0: Integer.parseInt(prefDaemon));
if (allDaemons == null || allDaemons.size() == 0 || daemonId < 0 || daemonId > allDaemons.size()) {
daemonSettings = null;
} else {
daemonSettings = allDaemons.get(daemonId);
}
// Read and parse layout
String prefLayout = prefs.getString(KEY_WIDGET_LAYOUT + widgetID, "style_black");
int layoutId = R.layout.appwidget_black;
if (prefLayout.equals("style_small")) {
layoutId = R.layout.appwidget_small;
} else if (prefLayout.equals("style_15")) {
layoutId = R.layout.appwidget_15;
} else if (prefLayout.equals("style_16")) {
layoutId = R.layout.appwidget_16;
} else if (prefLayout.equals("style_qsb")) {
layoutId = R.layout.appwidget_qsb;
} else if (prefLayout.equals("style_transparent")) {
layoutId = R.layout.appwidget_transparent;
}
// Return widget settings
return new WidgetSettings(
widgetID,
daemonSettings,
readWidgetIntervalSettin(prefs, widgetID),
layoutId);
}
/**
* Returns only the refresh interval setting for a certain widget
* @param prefs The preferences object to retrieve the settings from
* @param widgetId The id of the widget for which to get the setting
* @return The set refresh interval in seconds
*/
public static int readWidgetIntervalSettin(SharedPreferences prefs, int widgetId) {
return Integer.parseInt(prefs.getString(KEY_WIDGET_REFRESH + widgetId, "86400"));
}
/**
* Stores a new refresh interval value to the user settings. Don't
* forget to call readInterfaceSettings(prefs) to update these.
* @param prefs The preferences object to retrieve the settings from
* @param value The new interval as String (which is in R.array.pref_uirefresh_values)
*/
public static void storeNewRefreshInterval(SharedPreferences prefs, String value) {
Editor editor = prefs.edit();
editor.putString(KEY_PREF_UIREFRESH, value);
editor.commit();
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import org.transdroid.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PreferencesInterface extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_interface);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import android.content.Context;
import android.preference.RingtonePreference;
/**
* Wrapper class for RingtonePreference to expose the onClick() method
*
* @author erickok
*
*/
public class TransdroidNotificationListPreference extends RingtonePreference {
public TransdroidNotificationListPreference(Context context) { super(context); }
public void click() { onClick(); }
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import org.transdroid.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.text.InputType;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class PreferencesWebSearch extends PreferenceActivity {
public static final String PREFERENCES_WEBSITE_KEY = "PREFERENCES_WEBSITE_POSTFIX";
private static final String URL_FORMAT = "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?";
private String websitePostfix;
private TransdroidEditTextPreference name;
private TransdroidEditTextPreference url;
private String nameValue = null;
private String urlValue = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// For which server?
websitePostfix = getIntent().getStringExtra(PREFERENCES_WEBSITE_KEY);
// Create the preferences screen here: this takes care of saving/loading, but also contains the ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
nameValue = prefs.getString(Preferences.KEY_PREF_WEBSITE + websitePostfix, null);
urlValue = prefs.getString(Preferences.KEY_PREF_WEBURL + websitePostfix, null);
// Create preference objects
getPreferenceScreen().setTitle(R.string.pref_search);
// Name
name = new TransdroidEditTextPreference(this);
name.setTitle(R.string.pref_name);
name.setKey(Preferences.KEY_PREF_WEBSITE + websitePostfix);
name.getEditText().setSingleLine();
name.setDialogTitle(R.string.pref_name);
name.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(name);
// Url
url = new TransdroidEditTextPreference(this);
url.setTitle(R.string.pref_url);
url.setKey(Preferences.KEY_PREF_WEBURL + websitePostfix);
url.getEditText().setSingleLine();
url.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
url.setDialogTitle(R.string.pref_url_info);
url.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(url);
updateDescriptionTexts();
}
private OnPreferenceChangeListener updateHandler = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == name) {
nameValue = (String) newValue;
} else if (preference == url) {
urlValue = (String) newValue;
// Validate for a proper http(s) url
String newAddress = (String) newValue;
if (!newAddress.toLowerCase().matches(URL_FORMAT)) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_url_form, Toast.LENGTH_LONG).show();
return false;
}
}
updateDescriptionTexts();
// Set the value as usual
return true;
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference)item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference)item).click();
} else if (item instanceof TransdroidEditTextPreference) {
((TransdroidEditTextPreference)item).click();
}
}
private void updateDescriptionTexts() {
name.setSummary(nameValue == null? getText(R.string.pref_name_info): nameValue);
url.setSummary(urlValue == null? getText(R.string.pref_url_info): (urlValue.length() > 35? urlValue.substring(0, 35) + "...": urlValue));
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import java.net.URI;
import java.net.URISyntaxException;
import org.transdroid.R;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.OS;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ListView;
import android.widget.Toast;
public class PreferencesServer extends PreferenceActivity {
public static final String PREFERENCES_SERVER_KEY = "PREFERENCES_SERVER_POSTFIX";
private static final String IP_ADDRESS_FORMAT = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}";
// From http://regexlib.com/REDetails.aspx?regexp_id=829
private static final String IPv6_ADDRESS_FORMAT = "^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$";
// From http://stackoverflow.com/questions/1418423/the-hostname-regex
private static final String HOST_NAME_FORMAT = "^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\\b-){0,61}[0-9A-Za-z])?(?:\\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\\b-){0,61}[0-9A-Za-z])?)*\\.?$";
private String serverPostfix;
// These preferences are members so they can be accessed by the updateOptionAvailibility event
private TransdroidEditTextPreference name;
private TransdroidListPreference daemon;
private TransdroidEditTextPreference address;
private TransdroidEditTextPreference port;
private TransdroidCheckBoxPreference ssl;
private TransdroidCheckBoxPreference sslTrustAll;
private TransdroidEditTextPreference sslTrustKey;
private TransdroidEditTextPreference folder;
private TransdroidCheckBoxPreference auth;
private TransdroidEditTextPreference user;
private TransdroidEditTextPreference pass;
private TransdroidEditTextPreference extraPass;
private TransdroidListPreference os;
private TransdroidEditTextPreference downloadDir;
private TransdroidEditTextPreference ftpUrl;
private TransdroidEditTextPreference timeout;
private TransdroidCheckBoxPreference alarmFinished;
private TransdroidCheckBoxPreference alarmNew;
private String nameValue = null;
private String daemonValue = null;
private String addressValue = null;
private String portValue = null;
private boolean authValue = false;
private String userValue = null;
//private String passValue = null;
//private String extraPassValue = null;
private boolean sslValue = false;
private boolean sslTAValue = false;
private String sslTrustKeyValue = null;
private String folderValue = null;
private String osValue = null;
private String downloadDirValue = null;
private String ftpUrlValue = null;
private String timeoutValue = null;
//private boolean alarmFinishedValue = false;
//private boolean alarmNewValue = false;
// TODO: Allow setting of FTP password
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// For which server?
serverPostfix = getIntent().getStringExtra(PREFERENCES_SERVER_KEY);
// Create the preferences screen here: this takes care of saving/loading, but also contains the ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
nameValue = prefs.getString(Preferences.KEY_PREF_NAME + serverPostfix, null);
daemonValue = prefs.getString(Preferences.KEY_PREF_DAEMON + serverPostfix, null);
addressValue = prefs.getString(Preferences.KEY_PREF_ADDRESS + serverPostfix, null);
portValue = prefs.getString(Preferences.KEY_PREF_PORT + serverPostfix, null);
authValue = prefs.getBoolean(Preferences.KEY_PREF_AUTH + serverPostfix, false);
userValue = prefs.getString(Preferences.KEY_PREF_USER + serverPostfix, null);
//passValue = prefs.getString(Preferences.KEY_PREF_PASS + serverPostfix, null);
//extraPassValue = prefs.getString(Preferences.KEY_PREF_EXTRAPASS + serverPostfix, null);
sslValue = prefs.getBoolean(Preferences.KEY_PREF_SSL + serverPostfix, false);
//sslTAValue = prefs.getBoolean(Preferences.KEY_PREF_SSL_TRUST_ALL + serverPostfix, false);
sslTrustKeyValue = prefs.getString(Preferences.KEY_PREF_SSL_TRUST_KEY + serverPostfix, null);
folderValue = prefs.getString(Preferences.KEY_PREF_FOLDER + serverPostfix, null);
osValue = prefs.getString(Preferences.KEY_PREF_OS + serverPostfix, "type_windows");
downloadDirValue = prefs.getString(Preferences.KEY_PREF_DOWNLOADDIR + serverPostfix, null);
ftpUrlValue = prefs.getString(Preferences.KEY_PREF_FTPURL + serverPostfix, null);
timeoutValue = prefs.getString(Preferences.KEY_PREF_TIMEOUT + serverPostfix, null);
//alertFinishedValue = prefs.getBoolean(Preferences.KEY_PREF_ALERT_FINISHED + serverPostfix, true);
// Create preference objects
getPreferenceScreen().setTitle(R.string.pref_server);
// Basic
PreferenceCategory basic = new PreferenceCategory(this);
basic.setTitle(R.string.pref_basic);
getPreferenceScreen().addItemFromInflater(basic);
// Name
name = new TransdroidEditTextPreference(this);
name.setTitle(R.string.pref_name);
name.setKey(Preferences.KEY_PREF_NAME + serverPostfix);
name.getEditText().setSingleLine();
name.setDialogTitle(R.string.pref_name);
name.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(name);
// Daemon
daemon = new TransdroidListPreference(this);
daemon.setTitle(R.string.pref_daemon);
daemon.setKey(Preferences.KEY_PREF_DAEMON + serverPostfix);
daemon.setEntries(R.array.pref_daemon_types);
daemon.setEntryValues(R.array.pref_daemon_values);
daemon.setDialogTitle(R.string.pref_daemon);
daemon.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(daemon);
// Address
address = new TransdroidEditTextPreference(this);
address.setTitle(R.string.pref_address);
address.setKey(Preferences.KEY_PREF_ADDRESS + serverPostfix);
address.getEditText().setSingleLine();
address.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
address.setDialogTitle(R.string.pref_address);
address.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(address);
// Port
port = new TransdroidEditTextPreference(this);
port.setTitle(R.string.pref_port);
port.setKey(Preferences.KEY_PREF_PORT + serverPostfix);
port.getEditText().setSingleLine();
port.getEditText().setInputType(port.getEditText().getInputType() | EditorInfo.TYPE_CLASS_NUMBER);
port.setDialogTitle(R.string.pref_port);
port.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(port);
// Auth
auth = new TransdroidCheckBoxPreference(this);
auth.setTitle(R.string.pref_auth);
auth.setKey(Preferences.KEY_PREF_AUTH + serverPostfix);
auth.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(auth);
// User
user = new TransdroidEditTextPreference(this);
user.setTitle(R.string.pref_user);
user.setKey(Preferences.KEY_PREF_USER + serverPostfix);
user.getEditText().setSingleLine();
user.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER);
user.setDialogTitle(R.string.pref_user);
user.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(user);
// Pass
pass = new TransdroidEditTextPreference(this);
pass.setTitle(R.string.pref_pass);
pass.setKey(Preferences.KEY_PREF_PASS + serverPostfix);
pass.getEditText().setSingleLine();
pass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
pass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
pass.setDialogTitle(R.string.pref_pass);
pass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(pass);
// Folder
folder = new TransdroidEditTextPreference(this);
if (Daemon.fromCode(daemonValue) == Daemon.rTorrent) {
folder.setTitle(R.string.pref_folder);
folder.setSummary(R.string.pref_folder_info);
} else if (Daemon.fromCode(daemonValue) == Daemon.Tfb4rt){
folder.setTitle(R.string.pref_folder2);
folder.setSummary(R.string.pref_folder2_info);
} else {
folder.setTitle(R.string.pref_folder2);
folder.setSummary(R.string.pref_folder3_info);
}
folder.setKey(Preferences.KEY_PREF_FOLDER + serverPostfix);
folder.getEditText().setSingleLine();
folder.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
folder.setDialogTitle(R.string.pref_folder);
folder.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(folder);
// ExtraUser
extraPass = new TransdroidEditTextPreference(this);
extraPass.setTitle(R.string.pref_extrapass);
extraPass.setKey(Preferences.KEY_PREF_EXTRAPASS + serverPostfix);
extraPass.getEditText().setSingleLine();
extraPass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
extraPass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
extraPass.setDialogTitle(R.string.pref_extrapass);
extraPass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(extraPass);
// Advanced
PreferenceCategory advanced = new PreferenceCategory(this);
advanced.setTitle(R.string.pref_advanced);
getPreferenceScreen().addItemFromInflater(advanced);
// AlertFinished
alarmFinished = new TransdroidCheckBoxPreference(this);
alarmFinished.setDefaultValue(true);
alarmFinished.setTitle(R.string.pref_alarmfinished);
alarmFinished.setSummary(R.string.pref_alarmfinished_info);
alarmFinished.setKey(Preferences.KEY_PREF_ALARMFINISHED + serverPostfix);
alarmFinished.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmFinished);
// AlertNew
alarmNew = new TransdroidCheckBoxPreference(this);
alarmNew.setTitle(R.string.pref_alarmnew);
alarmNew.setSummary(R.string.pref_alarmnew_info);
alarmNew.setKey(Preferences.KEY_PREF_ALARMNEW + serverPostfix);
alarmNew.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmNew);
// OS
os = new TransdroidListPreference(this);
os.setTitle(R.string.pref_os);
os.setKey(Preferences.KEY_PREF_OS + serverPostfix);
os.setEntries(R.array.pref_os_types);
os.setEntryValues(R.array.pref_os_values);
os.setDialogTitle(R.string.pref_os);
os.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(os);
// Download directory
downloadDir = new TransdroidEditTextPreference(this);
downloadDir.setTitle(R.string.pref_downloaddir);
downloadDir.setSummary(R.string.pref_downloaddir_info);
downloadDir.setKey(Preferences.KEY_PREF_DOWNLOADDIR + serverPostfix);
downloadDir.getEditText().setSingleLine();
downloadDir.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
downloadDir.setDialogTitle(R.string.pref_downloaddir);
downloadDir.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(downloadDir);
// FTP URL
ftpUrl = new TransdroidEditTextPreference(this);
ftpUrl.setTitle(R.string.pref_ftpurl);
ftpUrl.setSummary(R.string.pref_ftpurl_info);
ftpUrl.setKey(Preferences.KEY_PREF_FTPURL + serverPostfix);
ftpUrl.getEditText().setSingleLine();
ftpUrl.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
ftpUrl.setDialogTitle(R.string.pref_ftpurl);
ftpUrl.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(ftpUrl);
// Timeout
timeout = new TransdroidEditTextPreference(this);
timeout.setTitle(R.string.pref_timeout);
timeout.setSummary(R.string.pref_timeout);
timeout.setKey(Preferences.KEY_PREF_TIMEOUT + serverPostfix);
timeout.getEditText().setSingleLine();
timeout.getEditText().setInputType(timeout.getEditText().getInputType() | EditorInfo.TYPE_CLASS_NUMBER);
timeout.setDialogTitle(R.string.pref_timeout);
timeout.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(timeout);
// SSL
ssl = new TransdroidCheckBoxPreference(this);
ssl.setTitle(R.string.pref_ssl);
ssl.setSummary(R.string.pref_ssl_info);
ssl.setKey(Preferences.KEY_PREF_SSL + serverPostfix);
ssl.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(ssl);
// SSL trust key
sslTrustKey = new TransdroidEditTextPreference(this);
sslTrustKey.setTitle(R.string.pref_ssl_trust_key);
sslTrustKey.setSummary(R.string.pref_ssl_trust_key_info);
sslTrustKey.getEditText().setSingleLine();
sslTrustKey.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER);
sslTrustKey.setDialogTitle(R.string.pref_ssl_trust_key);
sslTrustKey.setKey(Preferences.KEY_PREF_SSL_TRUST_KEY + serverPostfix);
sslTrustKey.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(sslTrustKey);
// SSL trust all
sslTrustAll = new TransdroidCheckBoxPreference(this);
sslTrustAll.setTitle(R.string.pref_ssl_trust_all);
sslTrustAll.setSummary(R.string.pref_ssl_trust_all_info);
sslTrustAll.setKey(Preferences.KEY_PREF_SSL_TRUST_ALL + serverPostfix);
sslTrustAll.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(sslTrustAll);
updateOptionAvailability();
updateDescriptionTexts();
}
private OnPreferenceChangeListener updateHandler = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == name) {
nameValue = (String) newValue;
} else if (preference == daemon) {
daemonValue = (String) newValue;
} else if (preference == address) {
addressValue = (String) newValue;
// Validate for an IP address or host name
String newAddress = (String) newValue;
if (!(newAddress.matches(IP_ADDRESS_FORMAT) || newAddress.matches(IPv6_ADDRESS_FORMAT) || newAddress.matches(HOST_NAME_FORMAT))) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_ip_or_hostname, Toast.LENGTH_LONG).show();
return false;
}
} else if (preference == port) {
portValue = (String) newValue;
// Validate user port input (should be non-empty; the text box already ensures that any input is actually a number)
if (((String)newValue).equals("")) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_port_number, Toast.LENGTH_LONG).show();
return false;
}
} else if (preference == auth) {
authValue = (Boolean) newValue;
} else if (preference == user) {
userValue = (String) newValue;
} else if (preference == pass) {
//passValue = (String) newValue;
} else if (preference == extraPass) {
//extraPassValue = (String) newValue;
} else if (preference == ssl) {
sslValue = (Boolean) newValue;
} else if (preference == sslTrustAll) {
sslTAValue = (Boolean) newValue;
} else if (preference == sslTrustKey) {
sslTrustKeyValue = (String) newValue;
} else if (preference == folder) {
folderValue = (String) newValue;
} else if (preference == os) {
osValue = (String) newValue;
} else if (preference == downloadDir) {
downloadDirValue = (String) newValue;
// Validate the final / or \
if (downloadDirValue != null && !downloadDirValue.equals("") && !(downloadDirValue.endsWith("/") || downloadDirValue.endsWith("\\"))) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_directory, Toast.LENGTH_LONG).show();
return false;
}
} else if (preference == ftpUrl) {
ftpUrlValue = (String) newValue;
// Do basic URL validation
if (ftpUrlValue != null && !ftpUrlValue.equals("")) {
try {
new URI(ftpUrlValue); // If parsing fails, it was not properly formatted
} catch (URISyntaxException e) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_url_form, Toast.LENGTH_LONG).show();
return false;
}
}
} else if (preference == timeout) {
timeoutValue = (String) newValue;
// Validate user port input (should be non-empty; the text box already ensures that any input is actually a number)
if (((String)newValue).equals("")) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_timeout, Toast.LENGTH_LONG).show();
return false;
}
} else if (preference == alarmFinished) {
//alarmFinishedValue = (Boolean) newValue;
} else if (preference == alarmNew) {
//alarmNewValue = (Boolean) newValue;
}
updateOptionAvailability();
updateDescriptionTexts();
// Set the value as usual
return true;
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference)item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference)item).click();
} else if (item instanceof TransdroidEditTextPreference) {
((TransdroidEditTextPreference)item).click();
}
}
private void updateOptionAvailability() {
// Use daemon factory to see if the newly selected daemon supports the feature
// Then set the availability of the options according to the (other) settings
Daemon daemonType = Daemon.fromCode(daemonValue);
user.setEnabled(authValue);
pass.setEnabled(authValue);
extraPass.setEnabled(Daemon.supportsExtraPassword(Daemon.fromCode(daemonValue)));
sslTrustAll.setEnabled(sslValue);
folder.setEnabled(daemonType == null? false: Daemon.supportsCustomFolder(daemonType));
downloadDir.setEnabled(daemonType == null? false: Daemon.needsManualPathSpecified(daemonType));
sslTrustKey.setEnabled(sslValue && !sslTAValue);
}
private void updateDescriptionTexts() {
// Update the 'summary' labels of all preferences to show their current value
Daemon daemonType = Daemon.fromCode(daemonValue);
name.setSummary(nameValue == null? getText(R.string.pref_name_info): nameValue);
daemon.setSummary(daemonType == null? "": daemonType.toString());
address.setSummary(addressValue == null? getText(R.string.pref_address_info): addressValue);
port.setSummary(portValue == null? getText(R.string.pref_port_info).toString().trim() + " " + Daemon.getDefaultPortNumber(daemonType, sslValue): portValue);
auth.setSummary(R.string.pref_auth_info);
user.setTitle(daemonType != null && Daemon.supportsUsernameForHttp(Daemon.fromCode(daemonValue)) ? getString(R.string.pref_user_forhttp)
: getString(R.string.pref_user));
user.setSummary(userValue == null? "": userValue);
if (daemonType == Daemon.rTorrent) {
folder.setTitle(R.string.pref_folder);
folder.setSummary(folderValue == null? getText(R.string.pref_folder_info): folderValue);
} else if (daemonType == Daemon.Tfb4rt) {
folder.setTitle(R.string.pref_folder2);
folder.setSummary(folderValue == null? getText(R.string.pref_folder2_info): folderValue);
} else {
folder.setTitle(R.string.pref_folder2);
folder.setSummary(folderValue == null? getText(R.string.pref_folder3_info): folderValue);
}
os.setSummary(osValue == null? "": OS.fromCode(osValue).toString());
downloadDir.setSummary(downloadDirValue == null? getText(R.string.pref_downloaddir_info): downloadDirValue);
ftpUrl.setSummary(ftpUrlValue == null? getText(R.string.pref_ftpurl_info): ftpUrlValue);
timeout.setSummary(timeoutValue == null? getText(R.string.pref_timeout_info): timeoutValue);
sslTrustKey.setSummary(sslTrustKeyValue == null ? getText(R.string.pref_ssl_trust_key_info) : sslTrustKeyValue );
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import android.content.Context;
import android.preference.Preference;
/**
* Wrapper class for ListPreference to expose the onClick() method
*
* @author erickok
*
*/
public class TransdroidButtonPreference extends Preference {
public TransdroidButtonPreference(Context context) { super(context); }
public void click() { onClick(); }
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import org.transdroid.R;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.view.View;
import android.widget.ListView;
public class PreferencesRssFeed extends PreferenceActivity {
public static final String PREFERENCES_FEED_KEY = "PREFERENCES_SERVER_POSTFIX";
//private static final String URL_FORMAT = "^(http|ftp|https)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,6}(/\\S*)?$";//"(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?";
private String feedPostfix;
private TransdroidEditTextPreference name;
private TransdroidEditTextPreference url;
private String nameValue = null;
private String urlValue = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// For which server?
feedPostfix = getIntent().getStringExtra(PREFERENCES_FEED_KEY);
// Create the preferences screen here: this takes care of saving/loading, but also contains the ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
nameValue = prefs.getString(Preferences.KEY_PREF_RSSNAME + feedPostfix, null);
urlValue = prefs.getString(Preferences.KEY_PREF_RSSURL + feedPostfix, null);
// Create preference objects
getPreferenceScreen().setTitle(R.string.pref_search);
// Name
name = new TransdroidEditTextPreference(this);
name.setTitle(R.string.pref_name);
name.setKey(Preferences.KEY_PREF_RSSNAME + feedPostfix);
name.getEditText().setSingleLine();
name.setDialogTitle(R.string.pref_name);
name.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(name);
// Url
url = new TransdroidEditTextPreference(this);
url.setTitle(R.string.pref_feed_url);
url.setKey(Preferences.KEY_PREF_RSSURL + feedPostfix);
url.getEditText().setSingleLine();
url.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
url.setDialogTitle(R.string.pref_feed_url);
url.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(url);
// NeedsAuth
TransdroidCheckBoxPreference needsAuth = new TransdroidCheckBoxPreference(this);
needsAuth.setTitle(R.string.pref_feed_needsauth);
needsAuth.setSummary(R.string.pref_feed_needsauth_info);
needsAuth.setKey(Preferences.KEY_PREF_RSSAUTH + feedPostfix);
needsAuth.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(needsAuth);
updateDescriptionTexts();
}
private OnPreferenceChangeListener updateHandler = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == name) {
nameValue = (String) newValue;
} else if (preference == url) {
urlValue = (String) newValue;
// Validate for a proper http(s) url
/*String newAddress = (String) newValue;
if (!newAddress.toLowerCase().matches(URL_FORMAT)) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_url_form, Toast.LENGTH_LONG).show();
return false;
}*/
}
updateDescriptionTexts();
// Set the value as usual
return true;
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference)item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference)item).click();
} else if (item instanceof TransdroidEditTextPreference) {
((TransdroidEditTextPreference)item).click();
}
}
private void updateDescriptionTexts() {
name.setSummary(nameValue == null? getText(R.string.pref_name_info): nameValue);
url.setSummary(urlValue == null? "": (urlValue.length() > 35? urlValue.substring(0, 35) + "...": urlValue));
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import android.content.Context;
import android.preference.CheckBoxPreference;
/**
* Wrapper class for CheckboxPreference to expose the onClick() method
*
* @author erickok
*
*/
public class TransdroidCheckBoxPreference extends CheckBoxPreference {
public TransdroidCheckBoxPreference(Context context) { super(context); }
public void click() { onClick(); }
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import net.margaritov.preference.colorpicker.ColorPickerPreference;
import org.transdroid.R;
import org.transdroid.service.BootReceiver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ListView;
public class PreferencesAlarm extends PreferenceActivity {
private SharedPreferences prefs;
private TransdroidCheckBoxPreference enable;
private TransdroidListPreference interval;
private TransdroidCheckBoxPreference checkRssFeeds;
private TransdroidCheckBoxPreference alarmPlaySound;
private TransdroidNotificationListPreference alarmSoundURI;
private TransdroidCheckBoxPreference alarmVibrate;
private ColorPickerPreference alarmColour;
private TransdroidCheckBoxPreference adwNotify;
private TransdroidCheckBoxPreference adwOnlyDl;
private TransdroidCheckBoxPreference checkForUpdates;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the preferences screen here: this takes care of saving/loading, but also contains the ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isEnabled = prefs.getBoolean(Preferences.KEY_PREF_ENABLEALARM, false);
boolean isAdwEnabled = prefs.getBoolean(Preferences.KEY_PREF_ADWNOTIFY, false);
// Create preference objects
getPreferenceScreen().setTitle(R.string.pref_alarm);
// Enable
enable = new TransdroidCheckBoxPreference(this);
enable.setTitle(R.string.pref_enablealarm);
enable.setSummary(R.string.pref_enablealarm_info);
enable.setKey(Preferences.KEY_PREF_ENABLEALARM);
getPreferenceScreen().addItemFromInflater(enable);
// Inteval
interval = new TransdroidListPreference(this);
interval.setTitle(R.string.pref_alarmtime);
interval.setSummary(R.string.pref_alarmtime_info);
interval.setKey(Preferences.KEY_PREF_ALARMINT);
interval.setEntries(R.array.pref_alarminterval_types);
interval.setEntryValues(R.array.pref_alarminterval_values);
interval.setDefaultValue("600");
interval.setDialogTitle(R.string.pref_alarmtime);
interval.setEnabled(isEnabled);
getPreferenceScreen().addItemFromInflater(interval);
// CheckRssFeeds
checkRssFeeds = new TransdroidCheckBoxPreference(this);
checkRssFeeds.setTitle(R.string.pref_checkrssfeeds);
checkRssFeeds.setSummary(R.string.pref_checkrssfeeds_info);
checkRssFeeds.setKey(Preferences.KEY_PREF_CHECKRSSFEEDS);
checkRssFeeds.setEnabled(isEnabled);
getPreferenceScreen().addItemFromInflater(checkRssFeeds);
// Alarm play sound
alarmPlaySound = new TransdroidCheckBoxPreference(this);
alarmPlaySound.setTitle(R.string.pref_alarmplaysound);
alarmPlaySound.setSummary(R.string.pref_alarmplaysound_info);
alarmPlaySound.setKey(Preferences.KEY_PREF_ALARMPLAYSOUND);
alarmPlaySound.setEnabled(isEnabled);
getPreferenceScreen().addItemFromInflater(alarmPlaySound);
// Alarm sound URI
alarmSoundURI = new TransdroidNotificationListPreference(this);
alarmSoundURI.setTitle(R.string.pref_alarmsounduri);
alarmSoundURI.setSummary(R.string.pref_alarmsounduri_info);
alarmSoundURI.setKey(Preferences.KEY_PREF_ALARMSOUNDURI);
alarmSoundURI.setRingtoneType(RingtoneManager.TYPE_NOTIFICATION | RingtoneManager.TYPE_ALARM);
alarmSoundURI.setShowDefault(true);
alarmSoundURI.setShowSilent(false);
alarmSoundURI.setEnabled(isEnabled);
getPreferenceScreen().addItemFromInflater(alarmSoundURI);
// Vibrate
alarmVibrate = new TransdroidCheckBoxPreference(this);
alarmVibrate.setTitle(R.string.pref_alarmvibrate);
alarmVibrate.setSummary(R.string.pref_alarmvibrate_info);
alarmVibrate.setKey(Preferences.KEY_PREF_ALARMVIBRATE);
alarmVibrate.setEnabled(isEnabled);
getPreferenceScreen().addItemFromInflater(alarmVibrate);
// Notification LED colour
alarmColour = new ColorPickerPreference(this);
alarmColour.setTitle(R.string.pref_alarmcolour);
alarmColour.setSummary(R.string.pref_alarmcolour_info);
alarmColour.setKey(Preferences.KEY_PREF_ALARMCOLOUR);
alarmColour.setAlphaSliderEnabled(false);
alarmColour.setDefaultValue(0xff7dbb21);
alarmColour.setEnabled(isEnabled);
getPreferenceScreen().addItemFromInflater(alarmColour);
// Enable ADW notifications
adwNotify = new TransdroidCheckBoxPreference(this);
adwNotify.setTitle(R.string.pref_adwnotify);
adwNotify.setSummary(R.string.pref_adwnotify_info);
adwNotify.setKey(Preferences.KEY_PREF_ADWNOTIFY);
adwNotify.setEnabled(isEnabled);
getPreferenceScreen().addItemFromInflater(adwNotify);
// Send ADW notifications
adwOnlyDl = new TransdroidCheckBoxPreference(this);
adwOnlyDl.setTitle(R.string.pref_adwonlydl);
adwOnlyDl.setSummary(R.string.pref_adwonlydl_info);
adwOnlyDl.setKey(Preferences.KEY_PREF_ADWONLYDL);
adwOnlyDl.setEnabled(isEnabled && isAdwEnabled);
getPreferenceScreen().addItemFromInflater(adwOnlyDl);
// Enable
checkForUpdates = new TransdroidCheckBoxPreference(this);
checkForUpdates.setTitle(R.string.pref_checkforupdates);
checkForUpdates.setSummary(R.string.pref_checkforupdates_info);
checkForUpdates.setKey(Preferences.KEY_PREF_CHECKUPDATES);
checkForUpdates.setDefaultValue(true);
getPreferenceScreen().addItemFromInflater(checkForUpdates);
prefs.registerOnSharedPreferenceChangeListener(changesHandler);
}
@Override
protected void onResume() {
prefs.registerOnSharedPreferenceChangeListener(changesHandler);
super.onResume();
}
@Override
protected void onPause() {
prefs.unregisterOnSharedPreferenceChangeListener(changesHandler);
super.onPause();
}
private OnSharedPreferenceChangeListener changesHandler = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(Preferences.KEY_PREF_CHECKUPDATES)) {
// Only the update checker setting changed
BootReceiver.cancelUpdateCheck();
boolean shouldCheckForUpdates = sharedPreferences.getBoolean(Preferences.KEY_PREF_CHECKUPDATES, true);
if (shouldCheckForUpdates) {
BootReceiver.startUpdateCheck(getApplicationContext());
}
return;
}
// First cancel the alarm
BootReceiver.cancelAlarm();
// Start the alarm again, if requested
boolean isEnabled = sharedPreferences.getBoolean(Preferences.KEY_PREF_ENABLEALARM, true);
if (isEnabled) {
BootReceiver.startAlarm(getApplicationContext());
}
boolean isAdwEnabled = sharedPreferences.getBoolean(Preferences.KEY_PREF_ADWNOTIFY, true);
// Adapt the option accordingly
interval.setEnabled(isEnabled);
checkRssFeeds.setEnabled(isEnabled);
alarmPlaySound.setEnabled(isEnabled);
alarmSoundURI.setEnabled(isEnabled);
alarmVibrate.setEnabled(isEnabled);
alarmColour.setEnabled(isEnabled);
adwNotify.setEnabled(isEnabled);
adwOnlyDl.setEnabled(isEnabled && isAdwEnabled);
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference)item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference)item).click();
} else if (item instanceof TransdroidEditTextPreference) {
((TransdroidEditTextPreference)item).click();
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.preferences;
import java.util.List;
import org.transdroid.R;
import org.transdroid.preferences.PreferencesAdapter.PreferencesListButton;
import org.transdroid.rss.RssFeedSettings;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
/**
* Provides an activity to create and edit the RSS feeds.
*
* @author erickok
*
*/
public class PreferencesRss extends ListActivity {
private static final int MENU_REMOVE_ID = 1;
private static final int MENU_MOVEUP_ID = 2;
private static final int MENU_MOVEDOWN_ID = 3;
PreferencesAdapter adapter;
int feedCount;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Make sure a context menu is created on long-presses
registerForContextMenu(getListView());
buildAdapter();
}
private void buildAdapter() {
// Build a list of RSS feed settings objects to show
List<RssFeedSettings> feeds = Preferences.readAllRssFeedSettings(prefs);
feedCount = feeds.size();
// Set the list items
adapter = new PreferencesAdapter(this, feeds, Integer.MIN_VALUE);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action depending on the clicked list item (note that dividers are ignored)
Object item = getListAdapter().getItem(position);
// Handle button clicks first
if (item instanceof PreferencesListButton) {
PreferencesListButton button = (PreferencesListButton) item;
if (button.getKey().equals(PreferencesAdapter.ADD_NEW_RSSFEED)) {
// What is the max current feed ID number?
int max = 0;
while (prefs.contains(Preferences.KEY_PREF_RSSURL + Integer.toString(max))) {
max++;
}
// Start a new rss feed settings screen
Intent i = new Intent(this, PreferencesRssFeed.class);
i.putExtra(PreferencesRssFeed.PREFERENCES_FEED_KEY, Integer.toString(max));
startActivityForResult(i, 0);
} else if (button.getKey().equals(PreferencesAdapter.ADD_EZRSS_FEED)) {
Intent i = new Intent(this, EzRssFeedBuilder.class);
startActivityForResult(i, 0);
}
} else if (item instanceof RssFeedSettings) {
RssFeedSettings feed = (RssFeedSettings) item;
// Open the feed settings edit activity for the clicked rss feed
Intent i = new Intent(this, PreferencesRssFeed.class);
i.putExtra(PreferencesRssFeed.PREFERENCES_FEED_KEY, feed.getKey());
startActivityForResult(i, 0);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// One of the server settings has been updated: refresh the list
buildAdapter();
}
@Override
public boolean onContextItemSelected(MenuItem item) {
int id = (int) ((AdapterContextMenuInfo) item.getMenuInfo()).id;
Object selected = adapter.getItem(id);
if (selected instanceof RssFeedSettings) {
if (item.getItemId() == MENU_REMOVE_ID) {
// Remove this RSS feed and reload this screen
Preferences.removeRssFeedSettings(prefs, (RssFeedSettings)selected);
buildAdapter();
return true;
} else if (item.getItemId() == MENU_MOVEUP_ID) {
// Move this RSS feed up and reload this screen
Preferences.moveRssFeedSettings(prefs, (RssFeedSettings)selected, true);
buildAdapter();
return true;
} else if (item.getItemId() == MENU_MOVEDOWN_ID) {
// Move this RSS feed up and reload this screen
Preferences.moveRssFeedSettings(prefs, (RssFeedSettings)selected, false);
buildAdapter();
return true;
}
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Allow removing of daemon and site settings
int id = (int) ((AdapterContextMenuInfo)menuInfo).id;
Object item = adapter.getItem(id);
// For RssFeedSettings, allow removing of the feed
if (item instanceof RssFeedSettings) {
menu.add(0, MENU_REMOVE_ID, 0, R.string.menu_remove);
// Allow moving up/down, if appropriate
if (id > 0) {
menu.add(0, MENU_MOVEUP_ID, 0, R.string.menu_moveup);
}
if (id < feedCount - 1) {
menu.add(0, MENU_MOVEDOWN_ID, 0, R.string.menu_movedown);
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.rss;
public final class RssFeedSettings {
final private String key;
final private String name;
final private String url;
final private boolean needsAuth;
private String lastNew;
public RssFeedSettings(String key, String name, String url, boolean needsAuth, String lastNew) {
this.key = key;
this.name = name;
this.url = url;
this.needsAuth = needsAuth;
this.lastNew = lastNew;
}
/**
* Returns the unique key for this feed settings object (used as postfix in storing this settings to the user preferences)
* @return The unique rss feed preferences (postfix) key
*/
public String getKey() {
return this.key;
}
/**
* The custom name of the RSS feed, as given by the user
* @return The feed name
*/
public String getName() {
return this.name;
}
/**
* The full url of the RSS feed
* @return The feed url as url-encoded string
*/
public String getUrl() {
return this.url;
}
/**
* Whether this feed is secured and requires authentication
* @return True if it is secured with some authentication mechanism
*/
public boolean needsAuthentication() {
return this.needsAuth;
}
/**
* Returns the url of the item that was the newest last time we checked this feed
* @return The last new item's url as url-encoded string
*/
public String getLastNew() {
return this.lastNew;
}
public void setLastNew(String lastNew) {
this.lastNew = lastNew;
}
}
| Java |
package org.example.qberticus.quickactions;
import org.transdroid.R;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.PopupWindow;
/**
* This class does most of the work of wrapping the {@link PopupWindow} so it's simpler to use.
*
* @author qberticus
*
*/
public class BetterPopupWindow {
protected final View anchor;
private final PopupWindow window;
private View root;
private Drawable background = null;
private final WindowManager windowManager;
/**
* Create a BetterPopupWindow
*
* @param anchor
* the view that the BetterPopupWindow will be displaying 'from'
*/
public BetterPopupWindow(View anchor) {
this.anchor = anchor;
this.window = new PopupWindow(anchor.getContext());
// when a touch even happens outside of the window
// make the window go away
this.window.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_OUTSIDE) {
BetterPopupWindow.this.window.dismiss();
return true;
}
return false;
}
});
this.windowManager = (WindowManager) this.anchor.getContext().getSystemService(Context.WINDOW_SERVICE);
onCreate();
}
/**
* Anything you want to have happen when created. Probably should create a view and setup the event listeners on
* child views.
*/
protected void onCreate() {}
/**
* In case there is stuff to do right before displaying.
*/
protected void onShow() {}
private void preShow() {
if(this.root == null) {
throw new IllegalStateException("setContentView was not called with a view to display.");
}
onShow();
if(this.background == null) {
this.window.setBackgroundDrawable(new BitmapDrawable());
} else {
this.window.setBackgroundDrawable(this.background);
}
// if using PopupWindow#setBackgroundDrawable this is the only values of the width and hight that make it work
// otherwise you need to set the background of the root viewgroup
// and set the popupwindow background to an empty BitmapDrawable
this.window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
this.window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
this.window.setTouchable(true);
this.window.setFocusable(true);
this.window.setOutsideTouchable(true);
this.window.setContentView(this.root);
}
public void setBackgroundDrawable(Drawable background) {
this.background = background;
}
/**
* Sets the content view. Probably should be called from {@link onCreate}
*
* @param root
* the view the popup will display
*/
public void setContentView(View root) {
this.root = root;
this.window.setContentView(root);
}
/**
* Will inflate and set the view from a resource id
*
* @param layoutResID
*/
public void setContentView(int layoutResID) {
LayoutInflater inflator =
(LayoutInflater) this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.setContentView(inflator.inflate(layoutResID, null));
}
/**
* If you want to do anything when {@link dismiss} is called
*
* @param listener
*/
public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
this.window.setOnDismissListener(listener);
}
/**
* Displays like a popdown menu from the anchor view
*/
public void showLikePopDownMenu() {
this.showLikePopDownMenu(0, 0);
}
/**
* Displays like a popdown menu from the anchor view.
*
* @param xOffset
* offset in X direction
* @param yOffset
* offset in Y direction
*/
public void showLikePopDownMenu(int xOffset, int yOffset) {
this.preShow();
this.window.setAnimationStyle(R.style.Animations_PopDownMenu);
this.window.showAsDropDown(this.anchor, xOffset, yOffset);
}
/**
* Displays like a QuickAction from the anchor view.
*/
public void showLikeQuickAction() {
this.showLikeQuickAction(0, 0);
}
/**
* Displays like a QuickAction from the anchor view.
*
* @param xOffset
* offset in the X direction
* @param yOffset
* offset in the Y direction
*/
public void showLikeQuickAction(int xOffset, int yOffset) {
this.preShow();
this.window.setAnimationStyle(R.style.Animations_GrowFromBottom);
int[] location = new int[2];
this.anchor.getLocationOnScreen(location);
Rect anchorRect =
new Rect(location[0], location[1], location[0] + this.anchor.getWidth(), location[1]
+ this.anchor.getHeight());
this.root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootWidth = this.root.getMeasuredWidth();
int rootHeight = this.root.getMeasuredHeight();
int screenWidth = this.windowManager.getDefaultDisplay().getWidth();
//int screenHeight = this.windowManager.getDefaultDisplay().getHeight();
int xPos = ((screenWidth - rootWidth) / 2) + xOffset;
int yPos = anchorRect.top - rootHeight + yOffset;
// display on bottom
if(rootHeight > anchorRect.top) {
yPos = anchorRect.bottom + yOffset;
this.window.setAnimationStyle(R.style.Animations_GrowFromTop);
}
this.window.showAtLocation(this.anchor, Gravity.NO_GRAVITY, xPos, yPos);
}
public void dismiss() {
this.window.dismiss();
}
}
| Java |
/*
* Taken from the 'Learning Android' project,;
* released as Public Domain software at
* http://github.com/digitalspaghetti/learning-android
* and modified heavily for Transdroid
*/
package org.ifies.android.sax;
import java.io.IOException;
import java.util.Date;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.util.FakeSocketFactory;
import org.transdroid.daemon.util.HttpHelper;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class RssParser extends DefaultHandler
{
/**
* The constructor for the RSS Parser
* @param url
*/
public RssParser(String url) {
this.urlString = url;
this.text = new StringBuilder();
}
/**
* Returns the feed as a RssFeed, which is a ListArray
* @return RssFeed rssFeed
*/
public Channel getChannel() {
return (this.channel);
}
public void parse() throws ParserConfigurationException, SAXException, IOException {
DefaultHttpClient httpclient = initialise();
HttpResponse result = httpclient.execute(new HttpGet(urlString));
//FileInputStream urlInputStream = new FileInputStream("/sdcard/rsstest2.txt");
SAXParserFactory spf = SAXParserFactory.newInstance();
if (spf != null) {
SAXParser sp = spf.newSAXParser();
sp.parse(result.getEntity().getContent(), this);
}
}
/**
* Instantiates an HTTP client that can be used for all Torrentflux-b4rt requests.
* @param connectionTimeout The connection timeout in milliseconds
* @return
* @throws DaemonException On conflicting or missing settings
*/
private DefaultHttpClient initialise() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", new PlainSocketFactory(), 80));
registry.register(new Scheme("https", new FakeSocketFactory(), 443));
HttpParams httpparams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparams, 5000);
HttpConnectionParams.setSoTimeout(httpparams, 5000);
DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry), httpparams);
httpclient.addRequestInterceptor(HttpHelper.gzipRequestInterceptor);
httpclient.addResponseInterceptor(HttpHelper.gzipResponseInterceptor);
return httpclient;
}
/**
* By default creates a standard Item (with title, description and links), which
* may to overriden to add more data.
* @return A possibly decorated Item instance
*/
protected Item createNewItem() {
return new Item();
}
public void startElement(String uri, String localName, String qName, Attributes attributes) {
/** First lets check for the channel */
if (localName.equalsIgnoreCase("channel")) {
this.channel = new Channel();
}
/** Now lets check for an item */
if (localName.equalsIgnoreCase("item") && (this.channel != null)) {
this.item = createNewItem();
this.channel.addItem(this.item);
}
/** Now lets check for an image */
if (localName.equalsIgnoreCase("image") && (this.channel != null)) {
this.imgStatus = true;
}
/** Checking for a enclosure */
if (localName.equalsIgnoreCase("enclosure")) {
/** Lets check we are in an item */
if (this.item != null && attributes != null && attributes.getLength() > 0) {
this.item.setEnclosureUrl(parseLink(attributes.getValue("url")));
this.item.setEnclosureType(attributes.getValue("type"));
}
}
}
/**
* This is where we actually parse for the elements contents
*/
public void endElement(String uri, String localName, String qName) {
/** Check we have an RSS Feed */
if (this.channel == null) {
return;
}
/** Check are at the end of an item */
if (localName.equalsIgnoreCase("item")) {
this.item = null;
}
/** Check we are at the end of an image */
if (localName.equalsIgnoreCase("image"))
this.imgStatus = false;
/** Now we need to parse which title we are in */
if (localName.equalsIgnoreCase("title"))
{
/** We are an item, so we set the item title */
if (this.item != null){
this.item.setTitle(this.text.toString().trim());
/** We are in an image */
} else {
this.channel.setTitle(this.text.toString().trim());
}
}
/** Now we are checking for a link */
if (localName.equalsIgnoreCase("link")) {
/** Check we are in an item **/
if (this.item != null) {
this.item.setLink(parseLink(this.text.toString()));
/** Check we are in an image */
} else if (this.imgStatus) {
this.channel.setImage(parseLink(this.text.toString()));
/** Check we are in a channel */
} else {
this.channel.setLink(parseLink(this.text.toString()));
}
}
/** Checking for a description */
if (localName.equalsIgnoreCase("description")) {
/** Lets check we are in an item */
if (this.item != null) {
this.item.setDescription(this.text.toString().trim());
/** Lets check we are in the channel */
} else {
this.channel.setDescription(this.text.toString().trim());
}
}
/** Checking for a pubdate */
if (localName.equalsIgnoreCase("pubDate")) {
/** Lets check we are in an item */
if (this.item != null) {
try {
this.item.setPubdate(new Date(Date.parse(this.text.toString().trim())));
} catch (Exception e) {
// Date is malformed (not parsable by Date.parse)
}
/** Lets check we are in the channel */
} else {
try {
this.channel.setPubDate(new Date(Date.parse(this.text.toString().trim())));
} catch (Exception e) {
// Date is malformed (not parsable by Date.parse)
}
}
}
/** Check for the category */
if (localName.equalsIgnoreCase("category") && (this.item != null)) {
this.channel.addCategory(this.text.toString().trim());
}
addAdditionalData(localName, this.item, this.text.toString());
this.text.setLength(0);
}
/**
* May be overridden to add additional data from tags that are not standard in RSS.
* Not used by this default RSS style parser.
* @param localName The tag name
* @param item The Item we are currently parsing
* @param text The new text content
*/
protected void addAdditionalData(String localName, Item item, String text) { }
public void characters(char[] ch, int start, int length) {
this.text.append(ch, start, length);
}
private String parseLink(String string) {
return string.trim();
}
private String urlString;
private Channel channel;
private StringBuilder text;
private Item item;
private boolean imgStatus;
} | Java |
/*
* Taken from the 'Learning Android' project,;
* released as Public Domain software at
* http://github.com/digitalspaghetti/learning-android
*/
package org.ifies.android.sax;
import java.util.Date;
public class Item implements Comparable<Item> {
public void setId(int id) {
this._id = id;
}
public int getId() {
return _id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
public void setLink(String link) {
this.link = link;
}
public String getLink() {
return this.link;
}
public void setPubdate(Date pubdate) {
this.pubDate = pubdate;
}
public Date getPubdate() {
return this.pubDate;
}
public void setEnclosureUrl(String enclosureUrl) {
this.enclosureUrl = enclosureUrl;
}
public void setEnclosureType(String enclosureType) {
this.enclosureType = enclosureType;
}
public String getEnclosureUrl() {
return this.enclosureUrl;
}
public String getEnclosureType() {
return this.enclosureType;
}
private int _id;
private String title;
private String link;
private String description;
private Date pubDate;
private String enclosureUrl;
private String enclosureType;
/**
* Returns 'the' item link, which preferably is the enclosure url, but otherwise the link (or null if that is empty too)
* @return A single link url to be used
*/
public String getTheLink() {
if (this.getEnclosureUrl() != null) {
return this.getEnclosureUrl();
} else {
return this.getLink();
}
}
/**
* CompareTo is used to compare (and sort) item based on their publication dates
*/
@Override
public int compareTo(Item another) {
if (another == null || this.pubDate == null || another.getPubdate() == null) {
return 0;
}
return this.pubDate.compareTo(another.getPubdate());
}
} | Java |
/*
* Taken from the 'Learning Android' project,;
* released as Public Domain software at
* http://github.com/digitalspaghetti/learning-android
*/
package org.ifies.android.sax;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Channel {
public Channel() {
setCategories(new ArrayList<String>());
setItems(new ArrayList<Item>());
}
public void setId(int id) {
m_Id = id;
}
public int getId() {
return m_Id;
}
public void setTitle(String title) {
m_Title = title;
}
public String getTitle() {
return m_Title;
}
public void setLink(String link) {
m_Link = link;
}
public String getLink() {
return m_Link;
}
public void setDescription(String description) {
m_Description = description;
}
public String getDescription() {
return m_Description;
}
public void setPubDate(Date date) {
m_PubDate = date;
}
public Date getPubDate() {
return m_PubDate;
}
public void setLastBuildDate(long lastBuildDate) {
m_LastBuildDate = lastBuildDate;
}
public long getLastBuildDate() {
return m_LastBuildDate;
}
public void setCategories(List<String> categories) {
m_Categories = categories;
}
public void addCategory(String category) {
m_Categories.add(category);
}
public List<String> getCategories() {
return m_Categories;
}
public void setItems(List<Item> items) {
m_Items = items;
}
public void addItem(Item item) {
m_Items.add(item);
}
public List<Item> getItems() {
return m_Items;
}
public void setImage(String image) {
m_Image = image;
}
public String getImage() {
return m_Image;
}
private int m_Id;
private String m_Title;
private String m_Link;
private String m_Description;
private Date m_PubDate;
private long m_LastBuildDate;
private List<String> m_Categories;
private List<Item> m_Items;
private String m_Image;
} | Java |
package com.xirvik.transdroid.preferences;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.OS;
import org.transdroid.daemon.util.HttpHelper;
public class XirvikSettings {
private static final String DEFAULT_NAME = "Xirvik";
private static final int TFB4RT_PORT = 443;
private static final String TFB4RT_FOLDER = "/tfx";
private static final int RTORRENT_PORT = 443;
public static final String RTORRENT_FOLDER = "/RPC2";
private static final int UTORRENT_PORT = 5010;
final private String name;
final private XirvikServerType type;
final private String server;
final private String folder;
final private String username;
final private String password;
final private boolean alarmOnFinishedDownload;
final private boolean alarmOnNewTorrent;
final private String idString;
public XirvikSettings(String name, XirvikServerType type, String server, String folder, String username,
String password, boolean alarmOnFinishedDownload, boolean alarmOnNewTorrent,
String idString) {
this.name = name;
this.type = type;
this.server = server;
this.folder = folder;
this.username = username;
this.password = password;
this.alarmOnFinishedDownload = alarmOnFinishedDownload;
this.alarmOnNewTorrent = alarmOnNewTorrent;
this.idString = idString;
}
public String getName() {
return (name == null || name.equals("")? DEFAULT_NAME: name);
}
public XirvikServerType getType() {
return type;
}
public String getServer() {
return server;
}
public String getFolder() {
return folder;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public boolean shouldAlarmOnFinishedDownload() {
return alarmOnFinishedDownload;
}
public boolean shouldAlarmOnNewTorrent() {
return alarmOnNewTorrent;
}
public String getIdString() {
return idString;
}
/**
* Builds a text that can be used by a human reader to identify this daemon settings
* @return A concatenation of username, address, port and folder, where applicable
*/
public String getHumanReadableIdentifier() {
return this.getUsername() + "@" + getServer();
}
@Override
public String toString() {
return getHumanReadableIdentifier();
}
public List<DaemonSettings> createDaemonSettings(int startID) {
List<DaemonSettings> daemons = new ArrayList<DaemonSettings>();
boolean isDedi = getType() == XirvikServerType.Dedicated;
if (getType() == XirvikServerType.Shared || isDedi) {
daemons.add(
new DaemonSettings(
getName() + (isDedi? " Torrentflux-b4rt": ""),
Daemon.Tfb4rt, getServer(), TFB4RT_PORT,
true, true, null,
TFB4RT_FOLDER, true, getUsername(), getPassword(), null,
OS.Linux, "/", "ftp://" + getName() + ":" + getServer() + "/",
getPassword(), HttpHelper.DEFAULT_CONNECTION_TIMEOUT, shouldAlarmOnFinishedDownload(),
shouldAlarmOnNewTorrent(), "" + startID++, true));
}
if (getType() == XirvikServerType.SharedRtorrent || getType() == XirvikServerType.SemiDedicated || isDedi) {
daemons.add(
new DaemonSettings(
getName() + (isDedi? " rTorrent": ""),
Daemon.rTorrent, getServer(), RTORRENT_PORT,
true, true, null,
getFolder(), true, getUsername(), getPassword(), null,
OS.Linux, "/", "ftp://" + getName() + ":" + getServer() + "/",
getPassword(), HttpHelper.DEFAULT_CONNECTION_TIMEOUT, shouldAlarmOnFinishedDownload(),
shouldAlarmOnNewTorrent(), "" + startID++, true));
}
if (isDedi) {
daemons.add(
new DaemonSettings(
getName() + " uTorrent",
Daemon.uTorrent, getServer(), UTORRENT_PORT,
false, false, null,
null, true, getUsername(), getPassword(), null,
OS.Linux, "/", "ftp://" + getName() + ":" + getServer() + "/",
getPassword(), HttpHelper.DEFAULT_CONNECTION_TIMEOUT, shouldAlarmOnFinishedDownload(),
shouldAlarmOnNewTorrent(), "" + startID++, true));
}
return daemons;
}
}
| Java |
package com.xirvik.transdroid.preferences;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum XirvikServerType {
Dedicated (1),
SemiDedicated (2),
Shared (3),
SharedRtorrent (4);
private int code;
private static final Map<Integer,XirvikServerType> lookup = new HashMap<Integer,XirvikServerType>();
static {
for(XirvikServerType s : EnumSet.allOf(XirvikServerType.class))
lookup.put(s.getCode(), s);
}
XirvikServerType(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static XirvikServerType getStatus(int code) {
return lookup.get(code);
}
/**
* Returns the type of xirvik server
* @param code A string with the code, similar to that used in arrays.xml
* @return The xirvik server type; or null if the code was null or empty
*/
public static XirvikServerType fromCode(String code) {
if (code == null) {
return null;
}
if (code.equals("type_dedicated")) {
return Dedicated;
}
if (code.equals("type_semi")) {
return SemiDedicated;
}
if (code.equals("type_shared")) {
return Shared;
}
if (code.equals("type_sharedrt")) {
return SharedRtorrent;
}
return null;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package com.xirvik.transdroid.preferences;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.transdroid.R;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.util.HttpHelper;
import org.transdroid.preferences.Preferences;
import org.transdroid.preferences.TransdroidCheckBoxPreference;
import org.transdroid.preferences.TransdroidEditTextPreference;
import org.transdroid.preferences.TransdroidListPreference;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ListView;
import android.widget.Toast;
public class PreferencesXirvikServer extends PreferenceActivity {
public static final String PREFERENCES_XSERVER_KEY = "PREFERENCES_XSERVER_POSTFIX";
/* public static final String[] validAddressStart = { "dedi", "semi" }; */
public static final String[] validAddressEnding = { ".xirvik.com", ".xirvik.net" };
private String serverPostfix;
// These preferences are members so they can be accessed by the updateOptionAvailibility event
private TransdroidEditTextPreference name;
private TransdroidListPreference type;
private TransdroidEditTextPreference server;
private TransdroidEditTextPreference folder;
private TransdroidEditTextPreference user;
private TransdroidEditTextPreference pass;
private TransdroidCheckBoxPreference alarmFinished;
private TransdroidCheckBoxPreference alarmNew;
private String nameValue = null;
private String typeValue = null;
private String serverValue = null;
private String folderValue = null;
private String userValue = null;
private String passValue = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// For which server?
serverPostfix = getIntent().getStringExtra(PREFERENCES_XSERVER_KEY);
// Create the preferences screen here: this takes care of saving/loading, but also contains the
// ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
nameValue = prefs.getString(Preferences.KEY_PREF_XNAME + serverPostfix, null);
typeValue = prefs.getString(Preferences.KEY_PREF_XTYPE + serverPostfix, null);
serverValue = prefs.getString(Preferences.KEY_PREF_XSERVER + serverPostfix, null);
folderValue = prefs.getString(Preferences.KEY_PREF_XFOLDER + serverPostfix, null);
userValue = prefs.getString(Preferences.KEY_PREF_XUSER + serverPostfix, null);
passValue = prefs.getString(Preferences.KEY_PREF_XPASS + serverPostfix, null);
// Create preference objects
getPreferenceScreen().setTitle(R.string.xirvik_pref_title);
// Name
name = new TransdroidEditTextPreference(this);
name.setTitle(R.string.pref_name);
name.setKey(Preferences.KEY_PREF_XNAME + serverPostfix);
name.getEditText().setSingleLine();
name.setDialogTitle(R.string.pref_name);
name.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(name);
// Type
type = new TransdroidListPreference(this);
type.setTitle(R.string.xirvik_pref_type);
type.setKey(Preferences.KEY_PREF_XTYPE + serverPostfix);
type.setEntries(R.array.pref_xirvik_types);
type.setEntryValues(R.array.pref_xirvik_values);
type.setDialogTitle(R.string.xirvik_pref_type);
type.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(type);
// Server
server = new TransdroidEditTextPreference(this);
server.setTitle(R.string.xirvik_pref_server);
server.setKey(Preferences.KEY_PREF_XSERVER + serverPostfix);
server.getEditText().setSingleLine();
server.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
server.setDialogTitle(R.string.xirvik_pref_server);
server.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(server);
// Folder
folder = new TransdroidEditTextPreference(this);
folder.setTitle(R.string.xirvik_pref_folder);
folder.setKey(Preferences.KEY_PREF_XFOLDER + serverPostfix);
folder.setEnabled(false);
folder.setSummary(R.string.xirvik_pref_setautomatically);
getPreferenceScreen().addItemFromInflater(folder);
// User
user = new TransdroidEditTextPreference(this);
user.setTitle(R.string.pref_user);
user.setKey(Preferences.KEY_PREF_XUSER + serverPostfix);
user.getEditText().setSingleLine();
user.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER);
user.setDialogTitle(R.string.pref_user);
user.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(user);
// Pass
pass = new TransdroidEditTextPreference(this);
pass.setTitle(R.string.pref_pass);
pass.setKey(Preferences.KEY_PREF_XPASS + serverPostfix);
pass.getEditText().setSingleLine();
pass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
pass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
pass.setDialogTitle(R.string.pref_pass);
pass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(pass);
// AlertFinished
alarmFinished = new TransdroidCheckBoxPreference(this);
alarmFinished.setDefaultValue(true);
alarmFinished.setTitle(R.string.pref_alarmfinished);
alarmFinished.setSummary(R.string.pref_alarmfinished_info);
alarmFinished.setKey(Preferences.KEY_PREF_XALARMFINISHED + serverPostfix);
alarmFinished.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmFinished);
// AlertNew
alarmNew = new TransdroidCheckBoxPreference(this);
alarmNew.setTitle(R.string.pref_alarmnew);
alarmNew.setSummary(R.string.pref_alarmnew_info);
alarmNew.setKey(Preferences.KEY_PREF_XALARMNEW + serverPostfix);
alarmNew.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmNew);
updateDescriptionTexts();
}
private OnPreferenceChangeListener updateHandler = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == name) {
nameValue = (String) newValue;
} else if (preference == type) {
typeValue = (String) newValue;
} else if (preference == server) {
String newServer = (String) newValue;
// Validate Xirvik server address
boolean valid = newServer != null && !newServer.equals("") && !(newServer.indexOf(" ") >= 0);
boolean validEnd = false;
for (int i = 0; i < validAddressEnding.length && valid; i++) {
validEnd |= newServer.endsWith(validAddressEnding[i]);
}
if (!valid || !validEnd) {
Toast
.makeText(getApplicationContext(), R.string.xirvik_error_invalid_servername, Toast.LENGTH_LONG)
.show();
return false;
}
serverValue = newServer;
} else if (preference == user) {
userValue = (String) newValue;
} else if (preference == pass) {
passValue = (String) newValue;
}
updateDescriptionTexts();
updateScgiMountFolder();
// Set the value as usual
return true;
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference) item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference) item).click();
} else if (item instanceof TransdroidEditTextPreference) {
if (((TransdroidEditTextPreference) item).isEnabled()) {
((TransdroidEditTextPreference) item).click();
}
}
}
private void updateScgiMountFolder() {
if (typeValue != null && XirvikServerType.fromCode(typeValue) == XirvikServerType.SharedRtorrent) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
// Get, from the server, the RPC SCGI mount address
DefaultHttpClient httpclient = HttpHelper.createStandardHttpClient(true, userValue, passValue,
true, null, HttpHelper.DEFAULT_CONNECTION_TIMEOUT, serverValue, 443);
String url = "https://" + serverValue + ":443/browsers_addons/transdroid_autoconf.txt";
HttpResponse request = httpclient.execute(new HttpGet(url));
InputStream stream = request.getEntity().getContent();
String folderVal = HttpHelper.ConvertStreamToString(stream).trim();
if (folderVal.startsWith("<?xml")) {
folderVal = null;
}
stream.close();
return folderVal;
} catch (DaemonException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(String result) {
storeScgiMountFolder(result);
}
}.execute();
} else {
// No need to retrieve this value
storeScgiMountFolder(XirvikSettings.RTORRENT_FOLDER);
}
}
protected void storeScgiMountFolder(String result) {
if (result == null) {
// The RPC SCGI mount folder address couldn't be retrieved, so we cannot continue: show an error
Toast.makeText(getApplicationContext(), R.string.xirvik_error_nofolder, Toast.LENGTH_LONG).show();
folder.setSummary(R.string.xirvik_error_nofolder);
result = "";
}
// Store the new folder setting
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor edit = prefs.edit();
edit.putString(Preferences.KEY_PREF_XFOLDER + serverPostfix, result);
edit.commit();
folderValue = result;
updateDescriptionTexts();
}
private void updateDescriptionTexts() {
// Update the 'summary' labels of all preferences to show their current value
XirvikServerType typeType = XirvikServerType.fromCode(typeValue);
name.setSummary(nameValue == null ? getText(R.string.pref_name_info) : nameValue);
type.setSummary(typeType == null ? getText(R.string.xirvik_pref_type_info) : typeType.toString());
server.setSummary(serverValue == null ? getText(R.string.xirvik_pref_server_info) : serverValue);
user.setSummary(userValue == null ? "" : userValue);
folder.setSummary(folderValue == null ? "" : folderValue);
}
}
| Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
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 com.commonsware.cwac.sacklist;
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Adapter that simply returns row views from a list.
*
* If you supply a size, you must implement newView(), to
* create a required view. The adapter will then cache these
* views.
*
* If you supply a list of views in the constructor, that
* list will be used directly. If any elements in the list
* are null, then newView() will be called just for those
* slots.
*
* Subclasses may also wish to override areAllItemsEnabled()
* (default: false) and isEnabled() (default: false), if some
* of their rows should be selectable.
*
* It is assumed each view is unique, and therefore will not
* get recycled.
*
* Note that this adapter is not designed for long lists. It
* is more for screens that should behave like a list. This
* is particularly useful if you combine this with other
* adapters (e.g., SectionedAdapter) that might have an
* arbitrary number of rows, so it all appears seamless.
*/
public class SackOfViewsAdapter extends BaseAdapter {
private List<View> views=null;
/**
* Constructor creating an empty list of views, but with
* a specified count. Subclasses must override newView().
*/
public SackOfViewsAdapter(int count) {
super();
views=new ArrayList<View>(count);
for (int i=0;i<count;i++) {
views.add(null);
}
}
/**
* Constructor wrapping a supplied list of views.
* Subclasses must override newView() if any of the elements
* in the list are null.
*/
public SackOfViewsAdapter(List<View> views) {
super();
this.views=views;
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
return(views.get(position));
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
return(views.size());
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
return(getCount());
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
return(position);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View result=views.get(position);
if (result==null) {
result=newView(position, parent);
views.set(position, result);
}
return(result);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
return(position);
}
/**
* Create a new View to go into the list at the specified
* position.
* @param position Position of the item whose data we want
* @param parent ViewGroup containing the returned View
*/
protected View newView(int position, ViewGroup parent) {
throw new RuntimeException("You must override newView()!");
}
} | Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
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 com.commonsware.cwac.merge;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import java.util.ArrayList;
import java.util.List;
import com.commonsware.cwac.sacklist.SackOfViewsAdapter;
/**
* Adapter that merges multiple child adapters and views
* into a single contiguous whole.
*
* Adapters used as pieces within MergeAdapter must
* have view type IDs monotonically increasing from 0. Ideally,
* adapters also have distinct ranges for their row ids, as
* returned by getItemId().
*
*/
public class MergeAdapter extends BaseAdapter {
private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>();
/**
* Stock constructor, simply chaining to the superclass.
*/
public MergeAdapter() {
super();
}
/**
* Adds a new adapter to the roster of things to appear
* in the aggregate list.
* @param adapter Source for row views for this section
*/
public void addAdapter(ListAdapter adapter) {
pieces.add(adapter);
adapter.registerDataSetObserver(new CascadeDataSetObserver());
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
*/
public void addView(View view) {
addView(view, false);
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
* @param enabled false if views are disabled, true if enabled
*/
public void addView(View view, boolean enabled) {
ArrayList<View> list=new ArrayList<View>(1);
list.add(view);
addViews(list, enabled);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
*/
public void addViews(List<View> views) {
addViews(views, false);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
* @param enabled false if views are disabled, true if enabled
*/
public void addViews(List<View> views, boolean enabled) {
if (enabled) {
addAdapter(new EnabledSackAdapter(views));
}
else {
addAdapter(new SackOfViewsAdapter(views));
}
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItem(position));
}
position-=size;
}
return(null);
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getCount();
}
return(total);
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getViewTypeCount();
}
return(Math.max(total, 1)); // needed for setListAdapter() before content add'
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
int typeOffset=0;
int result=-1;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
result=typeOffset+piece.getItemViewType(position);
break;
}
position-=size;
typeOffset+=piece.getViewTypeCount();
}
return(result);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.isEnabled(position));
}
position-=size;
}
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getView(position, convertView, parent));
}
position-=size;
}
return(null);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItemId(position));
}
position-=size;
}
return(-1);
}
private static class EnabledSackAdapter extends SackOfViewsAdapter {
public EnabledSackAdapter(List<View> views) {
super(views);
}
@Override
public boolean areAllItemsEnabled() {
return(true);
}
@Override
public boolean isEnabled(int position) {
return(true);
}
}
private class CascadeDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
} | Java |
package com.seedm8.transdroid.preferences;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.OS;
import org.transdroid.daemon.util.HttpHelper;
public class SeedM8Settings {
private static final String DEFAULT_NAME = "SeedM8";
final private String name;
final private String server;
final private String username;
final private int delugePort;
final private String delugePassword;
final private int transmissionPort;
final private String transmissionPassword;
final private String rtorrentPassword;
final private String sftpPassword;
final private boolean alarmOnFinishedDownload;
final private boolean alarmOnNewTorrent;
final private String idString;
public SeedM8Settings(String name, String server, String username, int delugePort,
String delugePassword, int transmissionPort, String transmissionPassword,
String rtorrentPassword, String sftpPassword, boolean alarmOnFinishedDownload, boolean alarmOnNewTorrent,
String idString) {
this.name = name;
this.server = server;
this.username = username;
this.delugePort = delugePort;
this.delugePassword = delugePassword;
this.transmissionPort = transmissionPort;
this.transmissionPassword = transmissionPassword;
this.rtorrentPassword = rtorrentPassword;
this.sftpPassword = sftpPassword;
this.alarmOnFinishedDownload = alarmOnFinishedDownload;
this.alarmOnNewTorrent = alarmOnNewTorrent;
this.idString = idString;
}
public String getName() {
return (name == null || name.equals("")? DEFAULT_NAME: name);
}
public String getServer() {
return server;
}
public String getUsername() {
return username;
}
public String getDelugePassword() {
return delugePassword;
}
public int getDelugePort() {
return delugePort;
}
public String getTransmissionPassword() {
return transmissionPassword;
}
public int getTransmissionPort() {
return transmissionPort;
}
public String getRtorrentPassword() {
return rtorrentPassword;
}
public String getSftpPassword() {
return sftpPassword;
}
public boolean shouldAlarmOnFinishedDownload() {
return alarmOnFinishedDownload;
}
public boolean shouldAlarmOnNewTorrent() {
return alarmOnNewTorrent;
}
public String getIdString() {
return idString;
}
/**
* Builds a text that can be used by a human reader to identify this daemon settings
* @return A concatenation of username, address, port and folder, where applicable
*/
public String getHumanReadableIdentifier() {
return this.getUsername() + "@" + getServer();
}
@Override
public String toString() {
return getHumanReadableIdentifier();
}
public List<DaemonSettings> createDaemonSettings(int startID) {
List<DaemonSettings> daemons = new ArrayList<DaemonSettings>();
// Deluge
if (getDelugePassword() != null && !getDelugePassword().equals("")) {
daemons.add(
new DaemonSettings(
getName() + " Deluge",
Daemon.Deluge,
getUsername() + "." + getServer(),
getDelugePort(),
false,
false,
null,
null,
true,
getUsername(),
getDelugePassword(),
getDelugePassword(),
OS.Linux,
null,
"sftp://" + getServer() + "/home/" + getUsername() + "/private/deluge/data/",
getSftpPassword(),
HttpHelper.DEFAULT_CONNECTION_TIMEOUT,
shouldAlarmOnFinishedDownload(),
shouldAlarmOnNewTorrent(), "" + startID++, true));
}
// Transmission
if (getTransmissionPassword() != null && !getTransmissionPassword().equals("")) {
daemons.add(
new DaemonSettings(
getName() + " Transmission",
Daemon.Transmission,
getServer(),
getTransmissionPort(),
false,
false,
null,
null,
true,
getUsername(),
getTransmissionPassword(),
null,
OS.Linux,
null,
"sftp://" + getServer() + "/home/" + getUsername() + "/private/transmission/data/",
getSftpPassword(),
HttpHelper.DEFAULT_CONNECTION_TIMEOUT,
shouldAlarmOnFinishedDownload(),
shouldAlarmOnNewTorrent(), "" + startID++, true));
}
// rTorrent
if (getRtorrentPassword() != null && !getRtorrentPassword().equals("")) {
daemons.add(
new DaemonSettings(
getName() + " rTorrent",
Daemon.rTorrent,
getUsername() + "." + getServer(),
80,
false,
false,
null,
"/" + getUsername() + "/RPC",
true,
"rutorrent",
getRtorrentPassword(),
null,
OS.Linux,
null,
"sftp://" + getUsername() + "@" + getServer() + "/home/" + getUsername() + "/private/rtorrent/data/",
getSftpPassword(),
HttpHelper.DEFAULT_CONNECTION_TIMEOUT,
shouldAlarmOnFinishedDownload(),
shouldAlarmOnNewTorrent(), "" + startID++, true));
}
return daemons;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package com.seedm8.transdroid.preferences;
import org.transdroid.R;
import org.transdroid.preferences.Preferences;
import org.transdroid.preferences.TransdroidCheckBoxPreference;
import org.transdroid.preferences.TransdroidEditTextPreference;
import org.transdroid.preferences.TransdroidListPreference;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ListView;
import android.widget.Toast;
public class PreferencesSeedM8Server extends PreferenceActivity {
public static final String PREFERENCES_8SERVER_KEY = "PREFERENCES_8SERVER_POSTFIX";
public static final String[] validAddressEnding = { ".seedm8.com" };
private String serverPostfix;
// These preferences are members so they can be accessed by the updateOptionAvailibility event
private TransdroidEditTextPreference name;
private TransdroidEditTextPreference server;
private TransdroidEditTextPreference user;
private TransdroidEditTextPreference dpass;
private TransdroidEditTextPreference dport;
private TransdroidEditTextPreference tpass;
private TransdroidEditTextPreference tport;
private TransdroidEditTextPreference rpass;
private TransdroidEditTextPreference spass;
private TransdroidCheckBoxPreference alarmFinished;
private TransdroidCheckBoxPreference alarmNew;
private String nameValue = null;
private String serverValue = null;
private String userValue = null;
private String dportValue;
private String tportValue;
//private String passValue = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// For which server?
serverPostfix = getIntent().getStringExtra(PREFERENCES_8SERVER_KEY);
// Create the preferences screen here: this takes care of saving/loading, but also contains the ListView adapter, etc.
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(this));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
nameValue = prefs.getString(Preferences.KEY_PREF_8NAME + serverPostfix, null);
serverValue = prefs.getString(Preferences.KEY_PREF_8SERVER + serverPostfix, null);
userValue = prefs.getString(Preferences.KEY_PREF_8USER + serverPostfix, null);
dportValue = prefs.getString(Preferences.KEY_PREF_8DPORT + serverPostfix, null);
tportValue = prefs.getString(Preferences.KEY_PREF_8TPORT + serverPostfix, null);
// Create preference objects
getPreferenceScreen().setTitle(R.string.seedm8_pref_title);
// Name
name = new TransdroidEditTextPreference(this);
name.setTitle(R.string.pref_name);
name.setKey(Preferences.KEY_PREF_8NAME + serverPostfix);
name.getEditText().setSingleLine();
name.setDialogTitle(R.string.pref_name);
name.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(name);
// Server
server = new TransdroidEditTextPreference(this);
server.setTitle(R.string.seedm8_pref_server);
server.setKey(Preferences.KEY_PREF_8SERVER + serverPostfix);
server.getEditText().setSingleLine();
server.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
server.setDialogTitle(R.string.seedm8_pref_server);
server.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(server);
// User
user = new TransdroidEditTextPreference(this);
user.setTitle(R.string.pref_user);
user.setKey(Preferences.KEY_PREF_8USER + serverPostfix);
user.getEditText().setSingleLine();
user.getEditText().setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER);
user.setDialogTitle(R.string.pref_user);
user.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(user);
// Deluge Port
dport = new TransdroidEditTextPreference(this);
dport.setTitle("Deluge " + getString(R.string.pref_port));
dport.setKey(Preferences.KEY_PREF_8DPORT + serverPostfix);
dport.getEditText().setSingleLine();
dport.getEditText().setInputType(dport.getEditText().getInputType() | EditorInfo.TYPE_CLASS_NUMBER);
dport.setDialogTitle(R.string.pref_port);
dport.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(dport);
// Deluge Pass
dpass = new TransdroidEditTextPreference(this);
dpass.setTitle("Deluge " + getString(R.string.pref_pass));
dpass.setKey(Preferences.KEY_PREF_8DPASS + serverPostfix);
dpass.getEditText().setSingleLine();
dpass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
dpass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
dpass.setDialogTitle(R.string.pref_pass);
dpass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(dpass);
// Transmission Port
tport = new TransdroidEditTextPreference(this);
tport.setTitle("Transmission " + getString(R.string.pref_port));
tport.setKey(Preferences.KEY_PREF_8TPORT + serverPostfix);
tport.getEditText().setSingleLine();
tport.getEditText().setInputType(tport.getEditText().getInputType() | EditorInfo.TYPE_CLASS_NUMBER);
tport.setDialogTitle(R.string.pref_port);
tport.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(tport);
// Transmission Pass
tpass = new TransdroidEditTextPreference(this);
tpass.setTitle("Transmission " + getString(R.string.pref_pass));
tpass.setKey(Preferences.KEY_PREF_8TPASS + serverPostfix);
tpass.getEditText().setSingleLine();
tpass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
tpass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
tpass.setDialogTitle(R.string.pref_pass);
tpass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(tpass);
// rTorrent Pass
rpass = new TransdroidEditTextPreference(this);
rpass.setTitle("rTorrent RPC " + getString(R.string.pref_pass));
rpass.setKey(Preferences.KEY_PREF_8RPASS + serverPostfix);
rpass.getEditText().setSingleLine();
rpass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
rpass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
rpass.setDialogTitle(R.string.pref_pass);
rpass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(rpass);
// SFTP Pass
spass = new TransdroidEditTextPreference(this);
spass.setTitle("SFTP " + getString(R.string.pref_pass));
spass.setKey(Preferences.KEY_PREF_8RPASS + serverPostfix);
spass.getEditText().setSingleLine();
spass.getEditText().setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
spass.getEditText().setTransformationMethod(new PasswordTransformationMethod());
spass.setDialogTitle(R.string.pref_pass);
spass.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(spass);
// AlertFinished
alarmFinished = new TransdroidCheckBoxPreference(this);
alarmFinished.setDefaultValue(true);
alarmFinished.setTitle(R.string.pref_alarmfinished);
alarmFinished.setSummary(R.string.pref_alarmfinished_info);
alarmFinished.setKey(Preferences.KEY_PREF_8ALARMFINISHED + serverPostfix);
alarmFinished.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmFinished);
// AlertNew
alarmNew = new TransdroidCheckBoxPreference(this);
alarmNew.setTitle(R.string.pref_alarmnew);
alarmNew.setSummary(R.string.pref_alarmnew_info);
alarmNew.setKey(Preferences.KEY_PREF_8ALARMNEW + serverPostfix);
alarmNew.setOnPreferenceChangeListener(updateHandler);
getPreferenceScreen().addItemFromInflater(alarmNew);
updateDescriptionTexts();
}
private OnPreferenceChangeListener updateHandler = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == name) {
nameValue = (String) newValue;
} else if (preference == server) {
String newServer = (String) newValue;
// Validate SeedM8 server address
boolean valid = newServer != null && !newServer.equals("") && newServer.indexOf(" ") == -1;
boolean validEnd = false;
for (int i = 0; i < validAddressEnding.length && valid; i++) {
validEnd |= newServer.endsWith(validAddressEnding[i]);
}
if (!valid || !validEnd) {
Toast.makeText(getApplicationContext(), R.string.seedm8_error_invalid_servername, Toast.LENGTH_LONG).show();
return false;
}
serverValue = newServer;
} else if (preference == user) {
userValue = (String) newValue;
} else if (preference == dport) {
dportValue = (String) newValue;
// Validate user port input (should be non-empty; the text box already ensures that any input is actually a number)
if (((String)newValue).equals("")) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_port_number, Toast.LENGTH_LONG).show();
return false;
}
} else if (preference == tport) {
tportValue = (String) newValue;
// Validate user port input (should be non-empty; the text box already ensures that any input is actually a number)
if (((String)newValue).equals("")) {
Toast.makeText(getApplicationContext(), R.string.error_invalid_port_number, Toast.LENGTH_LONG).show();
return false;
}
}
updateDescriptionTexts();
// Set the value as usual
return true;
}
};
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Perform click action, which always is a Preference
Preference item = (Preference) getListAdapter().getItem(position);
// Let the Preference open the right dialog
if (item instanceof TransdroidListPreference) {
((TransdroidListPreference)item).click();
} else if (item instanceof TransdroidCheckBoxPreference) {
((TransdroidCheckBoxPreference)item).click();
} else if (item instanceof TransdroidEditTextPreference) {
((TransdroidEditTextPreference)item).click();
}
}
private void updateDescriptionTexts() {
// Update the 'summary' labels of all preferences to show their current value
name.setSummary(nameValue == null? getText(R.string.pref_name_info): nameValue);
server.setSummary(serverValue == null? getText(R.string.seedm8_pref_server_info): serverValue);
user.setSummary(userValue == null? "": userValue);
dport.setSummary(dportValue == null? "": dportValue);
tport.setSummary(tportValue == null? "": tportValue);
}
}
| Java |
/*
* Copyright (C) 2010 Daniel Nilsson
*
* 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 net.margaritov.preference.colorpicker;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
/**
* This drawable that draws a simple white and gray chessboard pattern.
* It's pattern you will often see as a background behind a
* partly transparent image in many applications.
* @author Daniel Nilsson
*/
public class AlphaPatternDrawable extends Drawable {
private int mRectangleSize = 10;
private Paint mPaint = new Paint();
private Paint mPaintWhite = new Paint();
private Paint mPaintGray = new Paint();
private int numRectanglesHorizontal;
private int numRectanglesVertical;
/**
* Bitmap in which the pattern will be cahched.
*/
private Bitmap mBitmap;
public AlphaPatternDrawable(int rectangleSize) {
mRectangleSize = rectangleSize;
mPaintWhite.setColor(0xffffffff);
mPaintGray.setColor(0xffcbcbcb);
}
@Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mBitmap, null, getBounds(), mPaint);
}
@Override
public int getOpacity() {
return 0;
}
@Override
public void setAlpha(int alpha) {
throw new UnsupportedOperationException("Alpha is not supported by this drawwable.");
}
@Override
public void setColorFilter(ColorFilter cf) {
throw new UnsupportedOperationException("ColorFilter is not supported by this drawwable.");
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
int height = bounds.height();
int width = bounds.width();
numRectanglesHorizontal = (int) Math.ceil((width / mRectangleSize));
numRectanglesVertical = (int) Math.ceil(height / mRectangleSize);
generatePatternBitmap();
}
/**
* This will generate a bitmap with the pattern
* as big as the rectangle we were allow to draw on.
* We do this to chache the bitmap so we don't need to
* recreate it each time draw() is called since it
* takes a few milliseconds.
*/
private void generatePatternBitmap(){
if(getBounds().width() <= 0 || getBounds().height() <= 0){
return;
}
mBitmap = Bitmap.createBitmap(getBounds().width(), getBounds().height(), Config.ARGB_8888);
Canvas canvas = new Canvas(mBitmap);
Rect r = new Rect();
boolean verticalStartWhite = true;
for (int i = 0; i <= numRectanglesVertical; i++) {
boolean isWhite = verticalStartWhite;
for (int j = 0; j <= numRectanglesHorizontal; j++) {
r.top = i * mRectangleSize;
r.left = j * mRectangleSize;
r.bottom = r.top + mRectangleSize;
r.right = r.left + mRectangleSize;
canvas.drawRect(r, isWhite ? mPaintWhite : mPaintGray);
isWhite = !isWhite;
}
verticalStartWhite = !verticalStartWhite;
}
}
} | Java |
/*
* Copyright (C) 2010 Daniel Nilsson
*
* 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 net.margaritov.preference.colorpicker;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Displays a color picker to the user and allow them
* to select a color. A slider for the alpha channel is
* also available. Enable it by setting
* setAlphaSliderVisible(boolean) to true.
* @author Daniel Nilsson
*/
public class ColorPickerView extends View {
private final static int PANEL_SAT_VAL = 0;
private final static int PANEL_HUE = 1;
private final static int PANEL_ALPHA = 2;
/**
* The width in pixels of the border
* surrounding all color panels.
*/
private final static float BORDER_WIDTH_PX = 1;
/**
* The width in dp of the hue panel.
*/
private float HUE_PANEL_WIDTH = 30f;
/**
* The height in dp of the alpha panel
*/
private float ALPHA_PANEL_HEIGHT = 20f;
/**
* The distance in dp between the different
* color panels.
*/
private float PANEL_SPACING = 10f;
/**
* The radius in dp of the color palette tracker circle.
*/
private float PALETTE_CIRCLE_TRACKER_RADIUS = 5f;
/**
* The dp which the tracker of the hue or alpha panel
* will extend outside of its bounds.
*/
private float RECTANGLE_TRACKER_OFFSET = 2f;
private float mDensity = 1f;
private OnColorChangedListener mListener;
private Paint mSatValPaint;
private Paint mSatValTrackerPaint;
private Paint mHuePaint;
private Paint mHueTrackerPaint;
private Paint mAlphaPaint;
private Paint mAlphaTextPaint;
private Paint mBorderPaint;
private Shader mValShader;
private Shader mSatShader;
private Shader mHueShader;
private Shader mAlphaShader;
private int mAlpha = 0xff;
private float mHue = 360f;
private float mSat = 0f;
private float mVal = 0f;
private String mAlphaSliderText = "";
private int mSliderTrackerColor = 0xff1c1c1c;
private int mBorderColor = 0xff6E6E6E;
private boolean mShowAlphaPanel = false;
/*
* To remember which panel that has the "focus" when
* processing hardware button data.
*/
private int mLastTouchedPanel = PANEL_SAT_VAL;
/**
* Offset from the edge we must have or else
* the finger tracker will get clipped when
* it is drawn outside of the view.
*/
private float mDrawingOffset;
/*
* Distance form the edges of the view
* of where we are allowed to draw.
*/
private RectF mDrawingRect;
private RectF mSatValRect;
private RectF mHueRect;
private RectF mAlphaRect;
private AlphaPatternDrawable mAlphaPattern;
private Point mStartTouchPoint = null;
public interface OnColorChangedListener {
public void onColorChanged(int color);
}
public ColorPickerView(Context context){
this(context, null);
}
public ColorPickerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ColorPickerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
mDensity = getContext().getResources().getDisplayMetrics().density;
PALETTE_CIRCLE_TRACKER_RADIUS *= mDensity;
RECTANGLE_TRACKER_OFFSET *= mDensity;
HUE_PANEL_WIDTH *= mDensity;
ALPHA_PANEL_HEIGHT *= mDensity;
PANEL_SPACING = PANEL_SPACING * mDensity;
mDrawingOffset = calculateRequiredOffset();
initPaintTools();
//Needed for receiving trackball motion events.
setFocusable(true);
setFocusableInTouchMode(true);
}
private void initPaintTools(){
mSatValPaint = new Paint();
mSatValTrackerPaint = new Paint();
mHuePaint = new Paint();
mHueTrackerPaint = new Paint();
mAlphaPaint = new Paint();
mAlphaTextPaint = new Paint();
mBorderPaint = new Paint();
mSatValTrackerPaint.setStyle(Style.STROKE);
mSatValTrackerPaint.setStrokeWidth(2f * mDensity);
mSatValTrackerPaint.setAntiAlias(true);
mHueTrackerPaint.setColor(mSliderTrackerColor);
mHueTrackerPaint.setStyle(Style.STROKE);
mHueTrackerPaint.setStrokeWidth(2f * mDensity);
mHueTrackerPaint.setAntiAlias(true);
mAlphaTextPaint.setColor(0xff1c1c1c);
mAlphaTextPaint.setTextSize(14f * mDensity);
mAlphaTextPaint.setAntiAlias(true);
mAlphaTextPaint.setTextAlign(Align.CENTER);
mAlphaTextPaint.setFakeBoldText(true);
}
private float calculateRequiredOffset(){
float offset = Math.max(PALETTE_CIRCLE_TRACKER_RADIUS, RECTANGLE_TRACKER_OFFSET);
offset = Math.max(offset, BORDER_WIDTH_PX * mDensity);
return offset * 1.5f;
}
private int[] buildHueColorArray(){
int[] hue = new int[361];
int count = 0;
for(int i = hue.length -1; i >= 0; i--, count++){
hue[count] = Color.HSVToColor(new float[]{i, 1f, 1f});
}
return hue;
}
@Override
protected void onDraw(Canvas canvas) {
if(mDrawingRect.width() <= 0 || mDrawingRect.height() <= 0) return;
drawSatValPanel(canvas);
drawHuePanel(canvas);
drawAlphaPanel(canvas);
}
private void drawSatValPanel(Canvas canvas){
final RectF rect = mSatValRect;
if(BORDER_WIDTH_PX > 0){
mBorderPaint.setColor(mBorderColor);
canvas.drawRect(mDrawingRect.left, mDrawingRect.top, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint);
}
if (mValShader == null) {
mValShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom,
0xffffffff, 0xff000000, TileMode.CLAMP);
}
int rgb = Color.HSVToColor(new float[]{mHue,1f,1f});
mSatShader = new LinearGradient(rect.left, rect.top, rect.right, rect.top,
0xffffffff, rgb, TileMode.CLAMP);
ComposeShader mShader = new ComposeShader(mValShader, mSatShader, PorterDuff.Mode.MULTIPLY);
mSatValPaint.setShader(mShader);
canvas.drawRect(rect, mSatValPaint);
Point p = satValToPoint(mSat, mVal);
mSatValTrackerPaint.setColor(0xff000000);
canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS - 1f * mDensity, mSatValTrackerPaint);
mSatValTrackerPaint.setColor(0xffdddddd);
canvas.drawCircle(p.x, p.y, PALETTE_CIRCLE_TRACKER_RADIUS, mSatValTrackerPaint);
}
private void drawHuePanel(Canvas canvas){
final RectF rect = mHueRect;
if(BORDER_WIDTH_PX > 0){
mBorderPaint.setColor(mBorderColor);
canvas.drawRect(rect.left - BORDER_WIDTH_PX,
rect.top - BORDER_WIDTH_PX,
rect.right + BORDER_WIDTH_PX,
rect.bottom + BORDER_WIDTH_PX,
mBorderPaint);
}
if (mHueShader == null) {
mHueShader = new LinearGradient(rect.left, rect.top, rect.left, rect.bottom, buildHueColorArray(), null, TileMode.CLAMP);
mHuePaint.setShader(mHueShader);
}
canvas.drawRect(rect, mHuePaint);
float rectHeight = 4 * mDensity / 2;
Point p = hueToPoint(mHue);
RectF r = new RectF();
r.left = rect.left - RECTANGLE_TRACKER_OFFSET;
r.right = rect.right + RECTANGLE_TRACKER_OFFSET;
r.top = p.y - rectHeight;
r.bottom = p.y + rectHeight;
canvas.drawRoundRect(r, 2, 2, mHueTrackerPaint);
}
private void drawAlphaPanel(Canvas canvas){
if(!mShowAlphaPanel || mAlphaRect == null || mAlphaPattern == null) return;
final RectF rect = mAlphaRect;
if(BORDER_WIDTH_PX > 0){
mBorderPaint.setColor(mBorderColor);
canvas.drawRect(rect.left - BORDER_WIDTH_PX,
rect.top - BORDER_WIDTH_PX,
rect.right + BORDER_WIDTH_PX,
rect.bottom + BORDER_WIDTH_PX,
mBorderPaint);
}
mAlphaPattern.draw(canvas);
float[] hsv = new float[]{mHue,mSat,mVal};
int color = Color.HSVToColor(hsv);
int acolor = Color.HSVToColor(0, hsv);
mAlphaShader = new LinearGradient(rect.left, rect.top, rect.right, rect.top,
color, acolor, TileMode.CLAMP);
mAlphaPaint.setShader(mAlphaShader);
canvas.drawRect(rect, mAlphaPaint);
if(mAlphaSliderText != null && mAlphaSliderText!= ""){
canvas.drawText(mAlphaSliderText, rect.centerX(), rect.centerY() + 4 * mDensity, mAlphaTextPaint);
}
float rectWidth = 4 * mDensity / 2;
Point p = alphaToPoint(mAlpha);
RectF r = new RectF();
r.left = p.x - rectWidth;
r.right = p.x + rectWidth;
r.top = rect.top - RECTANGLE_TRACKER_OFFSET;
r.bottom = rect.bottom + RECTANGLE_TRACKER_OFFSET;
canvas.drawRoundRect(r, 2, 2, mHueTrackerPaint);
}
private Point hueToPoint(float hue){
final RectF rect = mHueRect;
final float height = rect.height();
Point p = new Point();
p.y = (int) (height - (hue * height / 360f) + rect.top);
p.x = (int) rect.left;
return p;
}
private Point satValToPoint(float sat, float val){
final RectF rect = mSatValRect;
final float height = rect.height();
final float width = rect.width();
Point p = new Point();
p.x = (int) (sat * width + rect.left);
p.y = (int) ((1f - val) * height + rect.top);
return p;
}
private Point alphaToPoint(int alpha){
final RectF rect = mAlphaRect;
final float width = rect.width();
Point p = new Point();
p.x = (int) (width - (alpha * width / 0xff) + rect.left);
p.y = (int) rect.top;
return p;
}
private float[] pointToSatVal(float x, float y){
final RectF rect = mSatValRect;
float[] result = new float[2];
float width = rect.width();
float height = rect.height();
if (x < rect.left){
x = 0f;
}
else if(x > rect.right){
x = width;
}
else{
x = x - rect.left;
}
if (y < rect.top){
y = 0f;
}
else if(y > rect.bottom){
y = height;
}
else{
y = y - rect.top;
}
result[0] = 1.f / width * x;
result[1] = 1.f - (1.f / height * y);
return result;
}
private float pointToHue(float y){
final RectF rect = mHueRect;
float height = rect.height();
if (y < rect.top){
y = 0f;
}
else if(y > rect.bottom){
y = height;
}
else{
y = y - rect.top;
}
return 360f - (y * 360f / height);
}
private int pointToAlpha(int x){
final RectF rect = mAlphaRect;
final int width = (int) rect.width();
if(x < rect.left){
x = 0;
}
else if(x > rect.right){
x = width;
}
else{
x = x - (int)rect.left;
}
return 0xff - (x * 0xff / width);
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
boolean update = false;
if(event.getAction() == MotionEvent.ACTION_MOVE){
switch(mLastTouchedPanel){
case PANEL_SAT_VAL:
float sat, val;
sat = mSat + x/50f;
val = mVal - y/50f;
if(sat < 0f){
sat = 0f;
}
else if(sat > 1f){
sat = 1f;
}
if(val < 0f){
val = 0f;
}
else if(val > 1f){
val = 1f;
}
mSat = sat;
mVal = val;
update = true;
break;
case PANEL_HUE:
float hue = mHue - y * 10f;
if(hue < 0f){
hue = 0f;
}
else if(hue > 360f){
hue = 360f;
}
mHue = hue;
update = true;
break;
case PANEL_ALPHA:
if(!mShowAlphaPanel || mAlphaRect == null){
update = false;
}
else{
int alpha = (int) (mAlpha - x*10);
if(alpha < 0){
alpha = 0;
}
else if(alpha > 0xff){
alpha = 0xff;
}
mAlpha = alpha;
update = true;
}
break;
}
}
if(update){
if(mListener != null){
mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}));
}
invalidate();
return true;
}
return super.onTrackballEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean update = false;
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
mStartTouchPoint = new Point((int)event.getX(), (int)event.getY());
update = moveTrackersIfNeeded(event);
break;
case MotionEvent.ACTION_MOVE:
update = moveTrackersIfNeeded(event);
break;
case MotionEvent.ACTION_UP:
mStartTouchPoint = null;
update = moveTrackersIfNeeded(event);
break;
}
if(update){
if(mListener != null){
mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}));
}
invalidate();
return true;
}
return super.onTouchEvent(event);
}
private boolean moveTrackersIfNeeded(MotionEvent event){
if(mStartTouchPoint == null) return false;
boolean update = false;
int startX = mStartTouchPoint.x;
int startY = mStartTouchPoint.y;
if(mHueRect.contains(startX, startY)){
mLastTouchedPanel = PANEL_HUE;
mHue = pointToHue(event.getY());
update = true;
}
else if(mSatValRect.contains(startX, startY)){
mLastTouchedPanel = PANEL_SAT_VAL;
float[] result = pointToSatVal(event.getX(), event.getY());
mSat = result[0];
mVal = result[1];
update = true;
}
else if(mAlphaRect != null && mAlphaRect.contains(startX, startY)){
mLastTouchedPanel = PANEL_ALPHA;
mAlpha = pointToAlpha((int)event.getX());
update = true;
}
return update;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 0;
int height = 0;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthAllowed = MeasureSpec.getSize(widthMeasureSpec);
int heightAllowed = MeasureSpec.getSize(heightMeasureSpec);
widthAllowed = chooseWidth(widthMode, widthAllowed);
heightAllowed = chooseHeight(heightMode, heightAllowed);
if(!mShowAlphaPanel){
height = (int) (widthAllowed - PANEL_SPACING - HUE_PANEL_WIDTH);
//If calculated height (based on the width) is more than the allowed height.
if(height > heightAllowed || getTag().equals("landscape")) {
height = heightAllowed;
width = (int) (height + PANEL_SPACING + HUE_PANEL_WIDTH);
}
else{
width = widthAllowed;
}
}
else{
width = (int) (heightAllowed - ALPHA_PANEL_HEIGHT + HUE_PANEL_WIDTH);
if(width > widthAllowed){
width = widthAllowed;
height = (int) (widthAllowed - HUE_PANEL_WIDTH + ALPHA_PANEL_HEIGHT);
}
else{
height = heightAllowed;
}
}
setMeasuredDimension(width, height);
}
private int chooseWidth(int mode, int size){
if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
return size;
} else { // (mode == MeasureSpec.UNSPECIFIED)
return getPrefferedWidth();
}
}
private int chooseHeight(int mode, int size){
if (mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
return size;
} else { // (mode == MeasureSpec.UNSPECIFIED)
return getPrefferedHeight();
}
}
private int getPrefferedWidth(){
int width = getPrefferedHeight();
if(mShowAlphaPanel){
width -= (PANEL_SPACING + ALPHA_PANEL_HEIGHT);
}
return (int) (width + HUE_PANEL_WIDTH + PANEL_SPACING);
}
private int getPrefferedHeight(){
int height = (int)(200 * mDensity);
if(mShowAlphaPanel){
height += PANEL_SPACING + ALPHA_PANEL_HEIGHT;
}
return height;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mDrawingRect = new RectF();
mDrawingRect.left = mDrawingOffset + getPaddingLeft();
mDrawingRect.right = w - mDrawingOffset - getPaddingRight();
mDrawingRect.top = mDrawingOffset + getPaddingTop();
mDrawingRect.bottom = h - mDrawingOffset - getPaddingBottom();
setUpSatValRect();
setUpHueRect();
setUpAlphaRect();
}
private void setUpSatValRect(){
final RectF dRect = mDrawingRect;
float panelSide = dRect.height() - BORDER_WIDTH_PX * 2;
if(mShowAlphaPanel){
panelSide -= PANEL_SPACING + ALPHA_PANEL_HEIGHT;
}
float left = dRect.left + BORDER_WIDTH_PX;
float top = dRect.top + BORDER_WIDTH_PX;
float bottom = top + panelSide;
float right = left + panelSide;
mSatValRect = new RectF(left,top, right, bottom);
}
private void setUpHueRect(){
final RectF dRect = mDrawingRect;
float left = dRect.right - HUE_PANEL_WIDTH + BORDER_WIDTH_PX;
float top = dRect.top + BORDER_WIDTH_PX;
float bottom = dRect.bottom - BORDER_WIDTH_PX - (mShowAlphaPanel ? (PANEL_SPACING + ALPHA_PANEL_HEIGHT) : 0);
float right = dRect.right - BORDER_WIDTH_PX;
mHueRect = new RectF(left, top, right, bottom);
}
private void setUpAlphaRect() {
if(!mShowAlphaPanel) return;
final RectF dRect = mDrawingRect;
float left = dRect.left + BORDER_WIDTH_PX;
float top = dRect.bottom - ALPHA_PANEL_HEIGHT + BORDER_WIDTH_PX;
float bottom = dRect.bottom - BORDER_WIDTH_PX;
float right = dRect.right - BORDER_WIDTH_PX;
mAlphaRect = new RectF(left, top, right, bottom);
mAlphaPattern = new AlphaPatternDrawable((int) (5 * mDensity));
mAlphaPattern.setBounds(
Math.round(mAlphaRect.left),
Math.round(mAlphaRect.top),
Math.round(mAlphaRect.right),
Math.round(mAlphaRect.bottom)
);
}
/**
* Set a OnColorChangedListener to get notified when the color
* selected by the user has changed.
* @param listener
*/
public void setOnColorChangedListener(OnColorChangedListener listener){
mListener = listener;
}
/**
* Set the color of the border surrounding all panels.
* @param color
*/
public void setBorderColor(int color){
mBorderColor = color;
invalidate();
}
/**
* Get the color of the border surrounding all panels.
*/
public int getBorderColor(){
return mBorderColor;
}
/**
* Get the current color this view is showing.
* @return the current color.
*/
public int getColor(){
return Color.HSVToColor(mAlpha, new float[]{mHue,mSat,mVal});
}
/**
* Set the color the view should show.
* @param color The color that should be selected.
*/
public void setColor(int color){
setColor(color, false);
}
/**
* Set the color this view should show.
* @param color The color that should be selected.
* @param callback If you want to get a callback to
* your OnColorChangedListener.
*/
public void setColor(int color, boolean callback){
int alpha = Color.alpha(color);
int red = Color.red(color);
int blue = Color.blue(color);
int green = Color.green(color);
float[] hsv = new float[3];
Color.RGBToHSV(red, green, blue, hsv);
mAlpha = alpha;
mHue = hsv[0];
mSat = hsv[1];
mVal = hsv[2];
if(callback && mListener != null){
mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal}));
}
invalidate();
}
/**
* Get the drawing offset of the color picker view.
* The drawing offset is the distance from the side of
* a panel to the side of the view minus the padding.
* Useful if you want to have your own panel below showing
* the currently selected color and want to align it perfectly.
* @return The offset in pixels.
*/
public float getDrawingOffset(){
return mDrawingOffset;
}
/**
* Set if the user is allowed to adjust the alpha panel. Default is false.
* If it is set to false no alpha will be set.
* @param visible
*/
public void setAlphaSliderVisible(boolean visible){
if(mShowAlphaPanel != visible){
mShowAlphaPanel = visible;
/*
* Reset all shader to force a recreation.
* Otherwise they will not look right after
* the size of the view has changed.
*/
mValShader = null;
mSatShader = null;
mHueShader = null;
mAlphaShader = null;;
requestLayout();
}
}
public void setSliderTrackerColor(int color){
mSliderTrackerColor = color;
mHueTrackerPaint.setColor(mSliderTrackerColor);
invalidate();
}
public int getSliderTrackerColor(){
return mSliderTrackerColor;
}
/**
* Set the text that should be shown in the
* alpha slider. Set to null to disable text.
* @param res string resource id.
*/
public void setAlphaSliderText(int res){
String text = getContext().getString(res);
setAlphaSliderText(text);
}
/**
* Set the text that should be shown in the
* alpha slider. Set to null to disable text.
* @param text Text that should be shown.
*/
public void setAlphaSliderText(String text){
mAlphaSliderText = text;
invalidate();
}
/**
* Get the current value of the text
* that will be shown in the alpha
* slider.
* @return
*/
public String getAlphaSliderText(){
return mAlphaSliderText;
}
} | Java |
/*
* Copyright (C) 2010 Daniel Nilsson
*
* 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 net.margaritov.preference.colorpicker;
import org.transdroid.R;
import android.app.Dialog;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
public class ColorPickerDialog
extends
Dialog
implements
ColorPickerView.OnColorChangedListener,
View.OnClickListener {
private ColorPickerView mColorPicker;
private ColorPickerPanelView mOldColor;
private ColorPickerPanelView mNewColor;
private OnColorChangedListener mListener;
public interface OnColorChangedListener {
public void onColorChanged(int color);
}
public ColorPickerDialog(Context context, int initialColor) {
super(context);
init(initialColor);
}
private void init(int color) {
// To fight color branding.
getWindow().setFormat(PixelFormat.RGBA_8888);
setUp(color);
}
private void setUp(int color) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_color_picker, null);
setContentView(layout);
setTitle(R.string.dialog_color_picker);
mColorPicker = (ColorPickerView) layout.findViewById(R.id.color_picker_view);
mOldColor = (ColorPickerPanelView) layout.findViewById(R.id.old_color_panel);
mNewColor = (ColorPickerPanelView) layout.findViewById(R.id.new_color_panel);
((LinearLayout) mOldColor.getParent()).setPadding(
Math.round(mColorPicker.getDrawingOffset()),
0,
Math.round(mColorPicker.getDrawingOffset()),
0
);
mOldColor.setOnClickListener(this);
mNewColor.setOnClickListener(this);
mColorPicker.setOnColorChangedListener(this);
mOldColor.setColor(color);
mColorPicker.setColor(color, true);
}
@Override
public void onColorChanged(int color) {
mNewColor.setColor(color);
/*
if (mListener != null) {
mListener.onColorChanged(color);
}
*/
}
public void setAlphaSliderVisible(boolean visible) {
mColorPicker.setAlphaSliderVisible(visible);
}
/**
* Set a OnColorChangedListener to get notified when the color
* selected by the user has changed.
* @param listener
*/
public void setOnColorChangedListener(OnColorChangedListener listener){
mListener = listener;
}
public int getColor() {
return mColorPicker.getColor();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.new_color_panel) {
if (mListener != null) {
mListener.onColorChanged(mNewColor.getColor());
}
}
dismiss();
}
}
| Java |
/*
* Copyright (C) 2011 Sergey Margaritov
*
* 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 net.margaritov.preference.colorpicker;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Bitmap.Config;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
/**
* A preference type that allows a user to choose a time
* @author Sergey Margaritov
*/
public class ColorPickerPreference
extends
Preference
implements
Preference.OnPreferenceClickListener,
ColorPickerDialog.OnColorChangedListener {
View mView;
int mDefaultValue = Color.BLACK;
private int mValue = Color.BLACK;
private float mDensity = 0;
private boolean mAlphaSliderEnabled = false;
private static final String androidns = "http://schemas.android.com/apk/res/android";
public ColorPickerPreference(Context context) {
super(context);
init(context, null);
}
public ColorPickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public ColorPickerPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
onColorChanged(restoreValue ? getValue() : (Integer) defaultValue);
}
private void init(Context context, AttributeSet attrs) {
mDensity = getContext().getResources().getDisplayMetrics().density;
setOnPreferenceClickListener(this);
if (attrs != null) {
String defaultValue = attrs.getAttributeValue(androidns, "defaultValue");
if (defaultValue.startsWith("#")) {
try {
mDefaultValue = convertToColorInt(defaultValue);
} catch (NumberFormatException e) {
Log.e("ColorPickerPreference", "Wrong color: " + defaultValue);
mDefaultValue = convertToColorInt("#FF000000");
}
} else {
int resourceId = attrs.getAttributeResourceValue(androidns, "defaultValue", 0);
if (resourceId != 0) {
mDefaultValue = context.getResources().getInteger(resourceId);
}
}
mAlphaSliderEnabled = attrs.getAttributeBooleanValue(null, "alphaSlider", false);
}
mValue = mDefaultValue;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
mView = view;
setPreviewColor();
}
private void setPreviewColor() {
if (mView == null) return;
ImageView iView = new ImageView(getContext());
LinearLayout widgetFrameView = ((LinearLayout)mView.findViewById(android.R.id.widget_frame));
if (widgetFrameView == null) return;
widgetFrameView.setVisibility(View.VISIBLE);
widgetFrameView.setPadding(
widgetFrameView.getPaddingLeft(),
widgetFrameView.getPaddingTop(),
(int)(mDensity * 8),
widgetFrameView.getPaddingBottom()
);
// remove already create preview image
int count = widgetFrameView.getChildCount();
if (count > 0) {
widgetFrameView.removeViews(0, count);
}
widgetFrameView.addView(iView);
iView.setBackgroundDrawable(new AlphaPatternDrawable((int)(5 * mDensity)));
iView.setImageBitmap(getPreviewBitmap());
}
private Bitmap getPreviewBitmap() {
int d = (int) (mDensity * 31); //30dip
int color = getValue();
Bitmap bm = Bitmap.createBitmap(d, d, Config.ARGB_8888);
int w = bm.getWidth();
int h = bm.getHeight();
int c = color;
for (int i = 0; i < w; i++) {
for (int j = i; j < h; j++) {
c = (i <= 1 || j <= 1 || i >= w-2 || j >= h-2) ? Color.GRAY : color;
bm.setPixel(i, j, c);
if (i != j) {
bm.setPixel(j, i, c);
}
}
}
return bm;
}
public int getValue() {
try {
if (isPersistent()) {
mValue = getPersistedInt(mDefaultValue);
}
} catch (ClassCastException e) {
mValue = mDefaultValue;
}
return mValue;
}
@Override
public void onColorChanged(int color) {
if (isPersistent()) {
persistInt(color);
}
mValue = color;
setPreviewColor();
try {
getOnPreferenceChangeListener().onPreferenceChange(this, color);
} catch (NullPointerException e) {
}
}
public boolean onPreferenceClick(Preference preference) {
ColorPickerDialog picker = new ColorPickerDialog(getContext(), getValue());
picker.setOnColorChangedListener(this);
if (mAlphaSliderEnabled) {
picker.setAlphaSliderVisible(true);
}
picker.show();
return false;
}
/**
* Toggle Alpha Slider visibility (by default it's disabled)
* @param enable
*/
public void setAlphaSliderEnabled(boolean enable) {
mAlphaSliderEnabled = enable;
}
/**
* For custom purposes. Not used by ColorPickerPreferrence
* @param color
* @author Unknown
*/
public static String convertToARGB(int color) {
String alpha = Integer.toHexString(Color.alpha(color));
String red = Integer.toHexString(Color.red(color));
String green = Integer.toHexString(Color.green(color));
String blue = Integer.toHexString(Color.blue(color));
if (alpha.length() == 1) {
alpha = "0" + alpha;
}
if (red.length() == 1) {
red = "0" + red;
}
if (green.length() == 1) {
green = "0" + green;
}
if (blue.length() == 1) {
blue = "0" + blue;
}
return "#" + alpha + red + green + blue;
}
/**
* For custom purposes. Not used by ColorPickerPreferrence
* @param argb
* @throws NumberFormatException
* @author Unknown
*/
public static int convertToColorInt(String argb) throws NumberFormatException {
if (argb.startsWith("#")) {
argb = argb.replace("#", "");
}
int alpha = -1, red = -1, green = -1, blue = -1;
if (argb.length() == 8) {
alpha = Integer.parseInt(argb.substring(0, 2), 16);
red = Integer.parseInt(argb.substring(2, 4), 16);
green = Integer.parseInt(argb.substring(4, 6), 16);
blue = Integer.parseInt(argb.substring(6, 8), 16);
}
else if (argb.length() == 6) {
alpha = 255;
red = Integer.parseInt(argb.substring(0, 2), 16);
green = Integer.parseInt(argb.substring(2, 4), 16);
blue = Integer.parseInt(argb.substring(4, 6), 16);
}
return Color.argb(alpha, red, green, blue);
}
} | Java |
/*
* Copyright (C) 2010 Daniel Nilsson
*
* 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 net.margaritov.preference.colorpicker;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
/**
* This class draws a panel which which will be filled with a color which can be set.
* It can be used to show the currently selected color which you will get from
* the {@link ColorPickerView}.
* @author Daniel Nilsson
*
*/
public class ColorPickerPanelView extends View {
/**
* The width in pixels of the border
* surrounding the color panel.
*/
private final static float BORDER_WIDTH_PX = 1;
private float mDensity = 1f;
private int mBorderColor = 0xff6E6E6E;
private int mColor = 0xff000000;
private Paint mBorderPaint;
private Paint mColorPaint;
private RectF mDrawingRect;
private RectF mColorRect;
private AlphaPatternDrawable mAlphaPattern;
public ColorPickerPanelView(Context context){
this(context, null);
}
public ColorPickerPanelView(Context context, AttributeSet attrs){
this(context, attrs, 0);
}
public ColorPickerPanelView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
mBorderPaint = new Paint();
mColorPaint = new Paint();
mDensity = getContext().getResources().getDisplayMetrics().density;
}
@Override
protected void onDraw(Canvas canvas) {
final RectF rect = mColorRect;
if(BORDER_WIDTH_PX > 0){
mBorderPaint.setColor(mBorderColor);
canvas.drawRect(mDrawingRect, mBorderPaint);
}
if(mAlphaPattern != null){
mAlphaPattern.draw(canvas);
}
mColorPaint.setColor(mColor);
canvas.drawRect(rect, mColorPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mDrawingRect = new RectF();
mDrawingRect.left = getPaddingLeft();
mDrawingRect.right = w - getPaddingRight();
mDrawingRect.top = getPaddingTop();
mDrawingRect.bottom = h - getPaddingBottom();
setUpColorRect();
}
private void setUpColorRect(){
final RectF dRect = mDrawingRect;
float left = dRect.left + BORDER_WIDTH_PX;
float top = dRect.top + BORDER_WIDTH_PX;
float bottom = dRect.bottom - BORDER_WIDTH_PX;
float right = dRect.right - BORDER_WIDTH_PX;
mColorRect = new RectF(left,top, right, bottom);
mAlphaPattern = new AlphaPatternDrawable((int)(5 * mDensity));
mAlphaPattern.setBounds(
Math.round(mColorRect.left),
Math.round(mColorRect.top),
Math.round(mColorRect.right),
Math.round(mColorRect.bottom)
);
}
/**
* Set the color that should be shown by this view.
* @param color
*/
public void setColor(int color){
mColor = color;
invalidate();
}
/**
* Get the color currently show by this view.
* @return
*/
public int getColor(){
return mColor;
}
/**
* Set the color of the border surrounding the panel.
* @param color
*/
public void setBorderColor(int color){
mBorderColor = color;
invalidate();
}
/**
* Get the color of the border surrounding the panel.
*/
public int getBorderColor(){
return mBorderColor;
}
} | Java |
package org.xmlrpc.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
class XMLRPCSerializer {
static final String TAG_NAME = "name";
static final String TAG_MEMBER = "member";
static final String TAG_VALUE = "value";
static final String TAG_DATA = "data";
static final String TYPE_INT = "int";
static final String TYPE_I4 = "i4";
static final String TYPE_I8 = "i8";
static final String TYPE_DOUBLE = "double";
static final String TYPE_BOOLEAN = "boolean";
static final String TYPE_STRING = "string";
static final String TYPE_DATE_TIME_ISO8601 = "dateTime.iso8601";
static final String TYPE_BASE64 = "base64";
static final String TYPE_ARRAY = "array";
static final String TYPE_STRUCT = "struct";
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
@SuppressWarnings("unchecked")
static void serialize(XmlSerializer serializer, Object object ) throws IOException {
// check for scalar types:
if (object instanceof Integer || object instanceof Short || object instanceof Byte) {
serializer.startTag(null, TYPE_I4).text(object.toString()).endTag(null, TYPE_I4);
} else
if (object instanceof Long) {
serializer.startTag(null, TYPE_I8).text(object.toString()).endTag(null, TYPE_I8);
} else
if (object instanceof Double || object instanceof Float) {
serializer.startTag(null, TYPE_DOUBLE).text(object.toString()).endTag(null, TYPE_DOUBLE);
} else
if (object instanceof Boolean) {
Boolean bool = (Boolean) object;
String boolStr = bool.booleanValue() ? "1" : "0";
serializer.startTag(null, TYPE_BOOLEAN).text(boolStr).endTag(null, TYPE_BOOLEAN);
} else
if (object instanceof String) {
serializer.startTag(null, TYPE_STRING).text(object.toString()).endTag(null, TYPE_STRING);
} else
if (object instanceof Date || object instanceof Calendar) {
String dateStr = dateFormat.format(object);
serializer.startTag(null, TYPE_DATE_TIME_ISO8601).text(dateStr).endTag(null, TYPE_DATE_TIME_ISO8601);
} else
if (object instanceof byte[] ){
String value = new String(Base64Coder.encode((byte[])object));
serializer.startTag(null, TYPE_BASE64).text(value).endTag(null, TYPE_BASE64);
} else
if (object instanceof List) {
serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA);
List<Object> list = (List<Object>) object;
Iterator<Object> iter = list.iterator();
while (iter.hasNext()) {
Object o = iter.next();
serializer.startTag(null, TAG_VALUE);
serialize(serializer, o);
serializer.endTag(null, TAG_VALUE);
}
serializer.endTag(null, TAG_DATA).endTag(null, TYPE_ARRAY);
} else
if (object instanceof Object[]) {
serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA);
Object[] objects = (Object[]) object;
for (int i=0; i<objects.length; i++) {
Object o = objects[i];
serializer.startTag(null, TAG_VALUE);
serialize(serializer, o);
serializer.endTag(null, TAG_VALUE);
}
serializer.endTag(null, TAG_DATA).endTag(null, TYPE_ARRAY);
} else
if (object instanceof Map) {
serializer.startTag(null, TYPE_STRUCT);
Map<String, Object> map = (Map<String, Object>) object;
Iterator<Entry<String, Object>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Object> entry = iter.next();
String key = entry.getKey();
Object value = entry.getValue();
serializer.startTag(null, TAG_MEMBER);
serializer.startTag(null, TAG_NAME).text(key).endTag(null, TAG_NAME);
serializer.startTag(null, TAG_VALUE);
serialize(serializer, value);
serializer.endTag(null, TAG_VALUE);
serializer.endTag(null, TAG_MEMBER);
}
serializer.endTag(null, TYPE_STRUCT);
} else {
throw new IOException("Cannot serialize " + object);
}
}
static Object deserialize(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, null, TAG_VALUE);
parser.nextTag();
String typeNodeName = parser.getName();
Object obj;
if (typeNodeName.equals(TYPE_INT) || typeNodeName.equals(TYPE_I4)) {
String value = parser.nextText();
obj = Integer.parseInt(value);
} else
if (typeNodeName.equals(TYPE_I8)) {
String value = parser.nextText();
obj = Long.parseLong(value);
} else
if (typeNodeName.equals(TYPE_DOUBLE)) {
String value = parser.nextText();
obj = Double.parseDouble(value);
} else
if (typeNodeName.equals(TYPE_BOOLEAN)) {
String value = parser.nextText();
obj = value.equals("1") ? Boolean.TRUE : Boolean.FALSE;
} else
if (typeNodeName.equals(TYPE_STRING)) {
obj = parser.nextText();
} else
if (typeNodeName.equals(TYPE_DATE_TIME_ISO8601)) {
String value = parser.nextText();
try {
obj = dateFormat.parseObject(value);
} catch (ParseException e) {
throw new IOException("Cannot deserialize dateTime " + value);
}
} else
if (typeNodeName.equals(TYPE_BASE64)) {
String value = parser.nextText();
BufferedReader reader = new BufferedReader(new StringReader(value));
String line;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
obj = Base64Coder.decode(sb.toString());
} else
if (typeNodeName.equals(TYPE_ARRAY)) {
parser.nextTag(); // TAG_DATA (<data>)
parser.require(XmlPullParser.START_TAG, null, TAG_DATA);
parser.nextTag();
List<Object> list = new ArrayList<Object>();
while (parser.getName().equals(TAG_VALUE)) {
list.add(deserialize(parser));
parser.nextTag();
}
parser.require(XmlPullParser.END_TAG, null, TAG_DATA);
parser.nextTag(); // TAG_ARRAY (</array>)
parser.require(XmlPullParser.END_TAG, null, TYPE_ARRAY);
obj = list.toArray();
} else
if (typeNodeName.equals(TYPE_STRUCT)) {
parser.nextTag();
Map<String, Object> map = new HashMap<String, Object>();
while (parser.getName().equals(TAG_MEMBER)) {
String memberName = null;
Object memberValue = null;
while (true) {
parser.nextTag();
String name = parser.getName();
if (name.equals(TAG_NAME)) {
memberName = parser.nextText();
} else
if (name.equals(TAG_VALUE)) {
memberValue = deserialize(parser);
} else {
break;
}
}
if (memberName != null && memberValue != null) {
map.put(memberName, memberValue);
}
parser.require(XmlPullParser.END_TAG, null, TAG_MEMBER);
parser.nextTag();
}
parser.require(XmlPullParser.END_TAG, null, TYPE_STRUCT);
obj = map;
} else {
throw new IOException("Cannot deserialize " + parser.getName());
}
parser.nextTag(); // TAG_VALUE (</value>)
parser.require(XmlPullParser.END_TAG, null, TAG_VALUE);
return obj;
}
}
| Java |
package org.xmlrpc.android;
/**
* A Base64 Encoder/Decoder.
*
* <p>
* This class is used to encode and decode data in Base64 format as described in
* RFC 1521.
*
* <p>
* This is "Open Source" software and released under the <a
* href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br>
* It is provided "as is" without warranty of any kind.<br>
* Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br>
* Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br>
*
* <p>
* Version history:<br>
* 2003-07-22 Christian d'Heureuse (chdh): Module created.<br>
* 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br>
* 2006-11-21 chdh:<br>
* Method encode(String) renamed to encodeString(String).<br>
* Method decode(String) renamed to decodeString(String).<br>
* New method encode(byte[],int) added.<br>
* New method decode(String) added.<br>
*/
class Base64Coder {
// Mapping table from 6-bit nibbles to Base64 characters.
private static char[] map1 = new char[64];
static {
int i = 0;
for (char c = 'A'; c <= 'Z'; c++) {
map1[i++] = c;
}
for (char c = 'a'; c <= 'z'; c++) {
map1[i++] = c;
}
for (char c = '0'; c <= '9'; c++) {
map1[i++] = c;
}
map1[i++] = '+';
map1[i++] = '/';
}
// Mapping table from Base64 characters to 6-bit nibbles.
private static byte[] map2 = new byte[128];
static {
for (int i = 0; i < map2.length; i++) {
map2[i] = -1;
}
for (int i = 0; i < 64; i++) {
map2[map1[i]] = (byte) i;
}
}
/**
* Encodes a string into Base64 format. No blanks or line breaks are
* inserted.
*
* @param s
* a String to be encoded.
* @return A String with the Base64 encoded data.
*/
static String encodeString(String s) {
return new String(encode(s.getBytes()));
}
/**
* Encodes a byte array into Base64 format. No blanks or line breaks are
* inserted.
*
* @param in
* an array containing the data bytes to be encoded.
* @return A character array with the Base64 encoded data.
*/
static char[] encode(byte[] in) {
return encode(in, in.length);
}
/**
* Encodes a byte array into Base64 format. No blanks or line breaks are
* inserted.
*
* @param in
* an array containing the data bytes to be encoded.
* @param iLen
* number of bytes to process in <code>in</code>.
* @return A character array with the Base64 encoded data.
*/
static char[] encode(byte[] in, int iLen) {
int oDataLen = (iLen * 4 + 2) / 3; // output length without padding
int oLen = ((iLen + 2) / 3) * 4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '=';
op++;
out[op] = op < oDataLen ? map1[o3] : '=';
op++;
}
return out;
}
/**
* Decodes a string from Base64 format.
*
* @param s
* a Base64 String to be decoded.
* @return A String containing the decoded data.
* @throws IllegalArgumentException
* if the input is not valid Base64 encoded data.
*/
static String decodeString(String s) {
return new String(decode(s));
}
/**
* Decodes a byte array from Base64 format.
*
* @param s
* a Base64 String to be decoded.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException
* if the input is not valid Base64 encoded data.
*/
static byte[] decode(String s) {
return decode(s.toCharArray());
}
/**
* Decodes a byte array from Base64 format. No blanks or line breaks are
* allowed within the Base64 encoded data.
*
* @param in
* a character array containing the Base64 encoded data.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException
* if the input is not valid Base64 encoded data.
*/
static byte[] decode(char[] in) {
int iLen = in.length;
if (iLen % 4 != 0) {
throw new IllegalArgumentException(
"Length of Base64 encoded input string is not a multiple of 4.");
}
while (iLen > 0 && in[iLen - 1] == '=') {
iLen--;
}
int oLen = (iLen * 3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : 'A';
int i3 = ip < iLen ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) {
throw new IllegalArgumentException(
"Illegal character in Base64 encoded data.");
}
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) {
throw new IllegalArgumentException(
"Illegal character in Base64 encoded data.");
}
int o0 = (b0 << 2) | (b1 >>> 4);
int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);
int o2 = ((b2 & 3) << 6) | b3;
out[op++] = (byte) o0;
if (op < oLen) {
out[op++] = (byte) o1;
}
if (op < oLen) {
out[op++] = (byte) o2;
}
}
return out;
}
// Dummy constructor.
private Base64Coder() {
}
}
| Java |
package org.xmlrpc.android;
public class XMLRPCFault extends XMLRPCException {
/**
*
*/
private static final long serialVersionUID = 5676562456612956519L;
private String faultString;
private int faultCode;
public XMLRPCFault(String faultString, int faultCode) {
super("XMLRPC Fault: " + faultString + " [code " + faultCode + "]");
this.faultString = faultString;
this.faultCode = faultCode;
}
public String getFaultString() {
return faultString;
}
public int getFaultCode() {
return faultCode;
}
}
| Java |
package org.xmlrpc.android;
public class XMLRPCException extends Exception {
/**
*
*/
private static final long serialVersionUID = 7499675036625522379L;
public XMLRPCException(Exception e) {
super(e);
}
public XMLRPCException(String string) {
super(string);
}
}
| Java |
package org.xmlrpc.android;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URI;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
/**
* XMLRPCClient allows to call remote XMLRPC method.
*
* <p>
* The following table shows how XML-RPC types are mapped to java call parameters/response values.
* </p>
*
* <p>
* <table border="2" align="center" cellpadding="5">
* <thead><tr><th>XML-RPC Type</th><th>Call Parameters</th><th>Call Response</th></tr></thead>
*
* <tbody>
* <td>int, i4</td><td>byte<br />Byte<br />short<br />Short<br />int<br />Integer</td><td>int<br />Integer</td>
* </tr>
* <tr>
* <td>i8</td><td>long<br />Long</td><td>long<br />Long</td>
* </tr>
* <tr>
* <td>double</td><td>float<br />Float<br />double<br />Double</td><td>double<br />Double</td>
* </tr>
* <tr>
* <td>string</td><td>String</td><td>String</td>
* </tr>
* <tr>
* <td>boolean</td><td>boolean<br />Boolean</td><td>boolean<br />Boolean</td>
* </tr>
* <tr>
* <td>dateTime.iso8601</td><td>java.util.Date<br />java.util.Calendar</td><td>java.util.Date</td>
* </tr>
* <tr>
* <td>base64</td><td>byte[]</td><td>byte[]</td>
* </tr>
* <tr>
* <td>array</td><td>java.util.List<Object><br />Object[]</td><td>Object[]</td>
* </tr>
* <tr>
* <td>struct</td><td>java.util.Map<String, Object></td><td>java.util.Map<String, Object></td>
* </tr>
* </tbody>
* </table>
* </p>
*/
public class XMLRPCClient {
private static final String TAG_METHOD_CALL = "methodCall";
private static final String TAG_METHOD_NAME = "methodName";
private static final String TAG_METHOD_RESPONSE = "methodResponse";
private static final String TAG_PARAMS = "params";
private static final String TAG_PARAM = "param";
private static final String TAG_FAULT = "fault";
private static final String TAG_FAULT_CODE = "faultCode";
private static final String TAG_FAULT_STRING = "faultString";
private HttpClient client;
private HttpPost postMethod;
private XmlSerializer serializer;
private HttpParams httpParams;
/**
* XMLRPCClient constructor. Creates new instance based on server URI
* @param XMLRPC server URI
*/
public XMLRPCClient(HttpClient client, URI uri) {
postMethod = new HttpPost(uri);
postMethod.addHeader("Content-Type", "text/xml");
// WARNING
// I had to disable "Expect: 100-Continue" header since I had
// two second delay between sending http POST request and POST body
httpParams = postMethod.getParams();
HttpProtocolParams.setUseExpectContinue(httpParams, false);
this.client = client;
serializer = Xml.newSerializer();
}
/**
* Convenience constructor. Creates new instance based on server String address
* @param XMLRPC server address
*/
public XMLRPCClient(HttpClient client, String url) {
this(client, URI.create(url));
}
/**
* Call method with optional parameters. This is general method.
* If you want to call your method with 0-8 parameters, you can use more
* convenience call methods
*
* @param method name of method to call
* @param params parameters to pass to method (may be null if method has no parameters)
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object[] params) throws XMLRPCException {
return callXMLRPC(method, params);
}
/**
* Convenience method call with no parameters
*
* @param method name of method to call
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method) throws XMLRPCException {
return callXMLRPC(method, null);
}
/**
* Convenience method call with one parameter
*
* @param method name of method to call
* @param p0 method's parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0) throws XMLRPCException {
Object[] params = {
p0,
};
return callXMLRPC(method, params);
}
/**
* Convenience method call with two parameters
*
* @param method name of method to call
* @param p0 method's 1st parameter
* @param p1 method's 2nd parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0, Object p1) throws XMLRPCException {
Object[] params = {
p0, p1,
};
return callXMLRPC(method, params);
}
/**
* Convenience method call with three parameters
*
* @param method name of method to call
* @param p0 method's 1st parameter
* @param p1 method's 2nd parameter
* @param p2 method's 3rd parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0, Object p1, Object p2) throws XMLRPCException {
Object[] params = {
p0, p1, p2,
};
return callXMLRPC(method, params);
}
/**
* Convenience method call with four parameters
*
* @param method name of method to call
* @param p0 method's 1st parameter
* @param p1 method's 2nd parameter
* @param p2 method's 3rd parameter
* @param p3 method's 4th parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0, Object p1, Object p2, Object p3) throws XMLRPCException {
Object[] params = {
p0, p1, p2, p3,
};
return callXMLRPC(method, params);
}
/**
* Convenience method call with five parameters
*
* @param method name of method to call
* @param p0 method's 1st parameter
* @param p1 method's 2nd parameter
* @param p2 method's 3rd parameter
* @param p3 method's 4th parameter
* @param p4 method's 5th parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4) throws XMLRPCException {
Object[] params = {
p0, p1, p2, p3, p4,
};
return callXMLRPC(method, params);
}
/**
* Convenience method call with six parameters
*
* @param method name of method to call
* @param p0 method's 1st parameter
* @param p1 method's 2nd parameter
* @param p2 method's 3rd parameter
* @param p3 method's 4th parameter
* @param p4 method's 5th parameter
* @param p5 method's 6th parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5) throws XMLRPCException {
Object[] params = {
p0, p1, p2, p3, p4, p5,
};
return callXMLRPC(method, params);
}
/**
* Convenience method call with seven parameters
*
* @param method name of method to call
* @param p0 method's 1st parameter
* @param p1 method's 2nd parameter
* @param p2 method's 3rd parameter
* @param p3 method's 4th parameter
* @param p4 method's 5th parameter
* @param p5 method's 6th parameter
* @param p6 method's 7th parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6) throws XMLRPCException {
Object[] params = {
p0, p1, p2, p3, p4, p5, p6,
};
return callXMLRPC(method, params);
}
/**
* Convenience method call with eight parameters
*
* @param method name of method to call
* @param p0 method's 1st parameter
* @param p1 method's 2nd parameter
* @param p2 method's 3rd parameter
* @param p3 method's 4th parameter
* @param p4 method's 5th parameter
* @param p5 method's 6th parameter
* @param p6 method's 7th parameter
* @param p7 method's 8th parameter
* @return deserialized method return value
* @throws XMLRPCException
*/
public Object call(String method, Object p0, Object p1, Object p2, Object p3, Object p4, Object p5, Object p6, Object p7) throws XMLRPCException {
Object[] params = {
p0, p1, p2, p3, p4, p5, p6, p7,
};
return callXMLRPC(method, params);
}
/**
* Call method with optional parameters
*
* @param method name of method to call
* @param params parameters to pass to method (may be null if method has no parameters)
* @return deserialized method return value
* @throws XMLRPCException
*/
@SuppressWarnings("unchecked")
protected Object callXMLRPC(String method, Object[] params) throws XMLRPCException {
try {
// prepare POST body
StringWriter bodyWriter = new StringWriter();
serializer.setOutput(bodyWriter);
serializer.startDocument(null, null);
serializer.startTag(null, TAG_METHOD_CALL);
// set method name
serializer.startTag(null, TAG_METHOD_NAME).text(method).endTag(null, TAG_METHOD_NAME);
if (params != null && params.length != 0) {
// set method params
serializer.startTag(null, TAG_PARAMS);
for (int i=0; i<params.length; i++) {
serializer.startTag(null, TAG_PARAM).startTag(null, XMLRPCSerializer.TAG_VALUE);
XMLRPCSerializer.serialize(serializer, params[i]);
serializer.endTag(null, XMLRPCSerializer.TAG_VALUE).endTag(null, TAG_PARAM);
}
serializer.endTag(null, TAG_PARAMS);
}
serializer.endTag(null, TAG_METHOD_CALL);
serializer.endDocument();
// set POST body
HttpEntity entity = new StringEntity(bodyWriter.toString());
postMethod.setEntity(entity);
// execute HTTP POST request
HttpResponse response = client.execute(postMethod);
// check status code
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new XMLRPCException("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
}
// parse response stuff
//
// setup pull parser
XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
entity = response.getEntity();
//String temp = HttpHelper.ConvertStreamToString(entity.getContent());
Reader reader = new InputStreamReader(entity.getContent());
pullParser.setInput(reader);
// lets start pulling...
pullParser.nextTag();
pullParser.require(XmlPullParser.START_TAG, null, TAG_METHOD_RESPONSE);
pullParser.nextTag(); // either TAG_PARAMS (<params>) or TAG_FAULT (<fault>)
String tag = pullParser.getName();
if (tag.equals(TAG_PARAMS)) {
// normal response
pullParser.nextTag(); // TAG_PARAM (<param>)
pullParser.require(XmlPullParser.START_TAG, null, TAG_PARAM);
pullParser.nextTag(); // TAG_VALUE (<value>)
// no parser.require() here since its called in XMLRPCSerializer.deserialize() below
// deserialize result
Object obj = XMLRPCSerializer.deserialize(pullParser);
entity.consumeContent();
return obj;
} else
if (tag.equals(TAG_FAULT)) {
// fault response
pullParser.nextTag(); // TAG_VALUE (<value>)
// no parser.require() here since its called in XMLRPCSerializer.deserialize() below
// deserialize fault result
Map<String, Object> map = (Map<String, Object>) XMLRPCSerializer.deserialize(pullParser);
String faultString = (String) map.get(TAG_FAULT_STRING);
int faultCode = (Integer) map.get(TAG_FAULT_CODE);
entity.consumeContent();
throw new XMLRPCFault(faultString, faultCode);
} else {
entity.consumeContent();
throw new XMLRPCException("Bad tag <" + tag + "> in XMLRPC response - neither <params> nor <fault>");
}
} catch (XMLRPCException e) {
// catch & propagate XMLRPCException/XMLRPCFault
throw e;
} catch (Exception e) {
// wrap any other Exception(s) around XMLRPCException
throw new XMLRPCException(e);
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
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;
/**
* The daemon adapter from the Synology Download Station torrent client.
*
*/
public class SynologyAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "Synology daemon";
private DaemonSettings settings;
private DefaultHttpClient httpClient;
private String sid;
public SynologyAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
String tid;
try {
switch (task.getMethod()) {
case Retrieve:
return new RetrieveTaskSuccessResult((RetrieveTask) task, tasksList(), null);
case GetStats:
return null;
case GetTorrentDetails:
tid = task.getTargetTorrent().getUniqueID();
return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, torrentDetails(tid));
case GetFileList:
tid = task.getTargetTorrent().getUniqueID();
return new GetFileListTaskSuccessResult((GetFileListTask) task, fileList(tid));
case AddByFile:
return null;
case AddByUrl:
String url = ((AddByUrlTask)task).getUrl();
createTask(url);
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
String magnet = ((AddByMagnetUrlTask)task).getUrl();
createTask(magnet);
return new DaemonTaskSuccessResult(task);
case Remove:
tid = task.getTargetTorrent().getUniqueID();
removeTask(tid);
return new DaemonTaskSuccessResult(task);
case Pause:
tid = task.getTargetTorrent().getUniqueID();
pauseTask(tid);
return new DaemonTaskSuccessResult(task);
case PauseAll:
pauseAllTasks();
return new DaemonTaskSuccessResult(task);
case Resume:
tid = task.getTargetTorrent().getUniqueID();
resumeTask(tid);
return new DaemonTaskSuccessResult(task);
case ResumeAll:
resumeAllTasks();
return new DaemonTaskSuccessResult(task);
case SetDownloadLocation:
return null;
case SetFilePriorities:
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);
return new DaemonTaskSuccessResult(task);
case SetAlternativeMode:
default:
return null;
}
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
}
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
// Synology API
private String login() throws DaemonException {
DLog.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");
} 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 createTask(String uri) throws DaemonException {
try {
authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=create&uri=" + URLEncoder.encode(uri, "UTF-8")).ensureSuccess();
} catch (UnsupportedEncodingException e) {
// Never happens
throw new DaemonException(ExceptionType.UnexpectedResponse, e.toString());
}
}
private void removeTask(String tid) throws DaemonException {
List<String> tids = new ArrayList<String>();
tids.add(tid);
removeTasks(tids);
}
private void pauseTask(String tid) throws DaemonException {
List<String> tids = new ArrayList<String>();
tids.add(tid);
pauseTasks(tids);
}
private void resumeTask(String tid) throws DaemonException {
List<String> tids = new ArrayList<String>();
tids.add(tid);
resumeTasks(tids);
}
private void pauseAllTasks() throws DaemonException {
List<String> tids = new ArrayList<String>();
for (Torrent torrent: tasksList()) {
tids.add(torrent.getUniqueID());
}
pauseTasks(tids);
}
private void resumeAllTasks() throws DaemonException {
List<String> tids = new ArrayList<String>();
for (Torrent torrent: tasksList()) {
tids.add(torrent.getUniqueID());
}
resumeTasks(tids);
}
private void removeTasks(List<String> tids) throws DaemonException {
authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=delete&id=" + Collections2.joinString(tids, ",") + "").ensureSuccess();
}
private void pauseTasks(List<String> tids) throws DaemonException {
authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=pause&id=" + Collections2.joinString(tids, ",")).ensureSuccess();
}
private void resumeTasks(List<String> tids) throws DaemonException {
authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=resume&id=" + Collections2.joinString(tids, ",")).ensureSuccess();
}
private List<Torrent> tasksList() 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());
List<Torrent> result = new ArrayList<Torrent>();
for (int i = 0; i < jsonTasks.length(); i++) {
result.add(parseTorrent(i, jsonTasks.getJSONObject(i)));
}
return result;
} catch (JSONException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
}
private List<TorrentFile> fileList(String torrentId) throws DaemonException {
try {
List<TorrentFile> result = new ArrayList<TorrentFile>();
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 additional = jsonTask.getJSONObject("additional");
if (!additional.has("file")) return result;
JSONArray files = additional.getJSONArray("file");
for (int i = 0; i < files.length(); i++) {
JSONObject task = files.getJSONObject(i);
result.add(new TorrentFile(
task.getString("filename"),
task.getString("filename"),
null,
null,
task.getLong("size"),
task.getLong("size_downloaded"),
priority(task.getString("priority"))
));
}
return result;
} catch (JSONException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
}
private TorrentDetails torrentDetails(String torrentId) throws DaemonException {
List<String> trackers = new ArrayList<String>();
List<String> errors = new ArrayList<String>();
try {
JSONObject jsonTorrent = authGet("SYNO.DownloadStation.Task", "1", "DownloadStation/task.cgi", "&method=getinfo&id=" + torrentId + "&additional=tracker").getData().getJSONArray("tasks").getJSONObject(0);
JSONObject additional = jsonTorrent.getJSONObject("additional");
if (additional.has("tracker")) {
JSONArray tracker = additional.getJSONArray("tracker");
for (int i = 0; i < tracker.length(); i++) {
JSONObject t = tracker.getJSONObject(i);
if ("Success".equals(t.getString("status"))) {
trackers.add(t.getString("url"));
} else {
errors.add(t.getString("status"));
}
}
}
return new TorrentDetails(trackers, errors);
} catch (JSONException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
}
private Torrent parseTorrent(long id, JSONObject jsonTorrent) throws JSONException, DaemonException {
JSONObject additional = jsonTorrent.getJSONObject("additional");
JSONObject detail = additional.getJSONObject("detail");
JSONObject transfer = additional.getJSONObject("transfer");
long downloaded = transfer.getLong("size_downloaded");
int speed = transfer.getInt("speed_download");
long size = jsonTorrent.getLong("size");
Float eta = new Float(size - downloaded) / speed;
int totalPeers = 0;
if (additional.has("tracker")) {
JSONArray tracker = additional.getJSONArray("tracker");
for (int i = 0; i < tracker.length(); i++) {
JSONObject t = tracker.getJSONObject(i);
if ("Success".equals(t.getString("status"))) {
totalPeers += t.getInt("peers");
totalPeers += t.getInt("seeds");
}
}
}
return new Torrent(
id,
jsonTorrent.getString("id"),
jsonTorrent.getString("title"),
torrentStatus(jsonTorrent.getString("status")),
detail.getString("destination"),
speed,
transfer.getInt("speed_upload"),
detail.getInt("connected_leechers"),
detail.getInt("connected_seeders"),
totalPeers,
totalPeers,
eta.intValue(),
downloaded,
Integer.parseInt(transfer.getString("size_uploaded")),
size,
(size == 0) ? 0 : (new Float(downloaded) / size),
0,
jsonTorrent.getString("title"),
new Date(detail.getLong("create_time") * 1000),
null,
""
);
}
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;
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;
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 {
if (sid == null) {
sid = login();
}
return new SynoRequest(path, api, version).get(params + "&_sid=" + sid);
}
private DefaultHttpClient getHttpClient() throws DaemonException {
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;
}
}
private static class SynoResponse {
private final HttpResponse response;
public SynoResponse(HttpResponse response) {
this.response = response;
}
public JSONObject getData() throws DaemonException {
JSONObject json = getJson();
try {
if (json.getBoolean("success")) {
return json.getJSONObject("data");
} else {
DLog.e(LOG_NAME, "not a success: " + json.toString());
throw new DaemonException(ExceptionType.AuthenticationFailure, json.getString("error"));
}
} catch (JSONException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
}
public JSONObject getJson() throws DaemonException {
try {
HttpEntity entity = response.getEntity();
if (entity == null) {
DLog.e(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
}
// Read JSON response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
JSONObject json;
json = new JSONObject(result);
instream.close();
return json;
} catch (JSONException e) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Bad JSON");
} catch (IOException e) {
DLog.e(LOG_NAME, "getJson error: " + e.toString());
throw new DaemonException(ExceptionType.AuthenticationFailure, e.toString());
}
}
public void ensureSuccess() throws DaemonException {
JSONObject json = getJson();
try {
if (!json.getBoolean("success"))
throw new DaemonException(ExceptionType.UnexpectedResponse, json.getString("error"));
} catch (JSONException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.Comparator;
/**
* Implements a comparator for TorrentFile objects, which can be used to sort
* a list listing in the ways specified by the TorrentFilesSortBy enum
*
* @author erickok
*
*/
public class TorrentFilesComparator implements Comparator<TorrentFile> {
TorrentFilesSortBy sortBy;
boolean reversed;
/**
* Instantiate a torrent files comparator.
* @param sortBy The requested sorting property (Alphanumeric is used for unsupported properties that are requested)
* @param reversed If the sorting should be in reverse order
*/
public TorrentFilesComparator(TorrentFilesSortBy sortBy, boolean reversed) {
this.sortBy = sortBy;
this.reversed = reversed;
}
@Override
public int compare(TorrentFile file1, TorrentFile file2) {
if (!reversed) {
switch (sortBy) {
case PartDone:
return Float.compare(file1.getPartDone(), file2.getPartDone());
case TotalSize:
return new Long(file1.getTotalSize()).compareTo(file2.getTotalSize());
default:
return file1.getName().toLowerCase().compareTo(file2.getName().toLowerCase());
}
} else {
switch (sortBy) {
case PartDone:
return 0 - Float.compare(file1.getPartDone(), file2.getPartDone());
case TotalSize:
return 0 - new Long(file1.getTotalSize()).compareTo(file2.getTotalSize());
default:
return 0 - file1.getName().toLowerCase().compareTo(file2.getName().toLowerCase());
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.BitComet;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
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.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
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.HTTP;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
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.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByUrlTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
import org.transdroid.daemon.task.SetTransferRatesTask;
import org.transdroid.daemon.util.DLog;
import org.transdroid.daemon.util.HttpHelper;
import com.android.internalcopy.http.multipart.Part;
import com.android.internalcopy.http.multipart.MultipartEntity;
import com.android.internalcopy.http.multipart.BitCometFilePart;
import com.android.internalcopy.http.multipart.Utf8StringPart;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* The daemon adapter for the BitComet torrent client.
*
* @author SeNS (sensboston)
*
* 09/26/2012: added AJAX support for BitComet v.1.34 and up
* : added additional tasks support
*/
public class BitCometAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "BitComet daemon";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
public BitCometAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
// first, check client for the new AJAX interface (BitComet v.1.34 and up)
try {
String xmlResult = makeRequest("/panel/task_list_xml");
if (xmlResult.startsWith("<?xml", 0)) {
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseXmlTorrents(xmlResult), null);
}
} catch (Exception e) {
// it's probably an old client, parse HTML instead
String htmlResult = makeRequest("/panel/task_list");
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseHttpTorrents(htmlResult), null);
}
case GetFileList:
// Request files listing for a specific torrent
String fhash = ((GetFileListTask)task).getTargetTorrent().getUniqueID();
String fileListResult = makeRequest("/panel/task_detail", new BasicNameValuePair("id", fhash),
new BasicNameValuePair("show", "files"));
return new GetFileListTaskSuccessResult((GetFileListTask) task, parseHttpTorrentFiles(fileListResult,
fhash));
case AddByFile:
// Upload a local .torrent file
String ufile = ((AddByFileTask)task).getFile();
makeFileUploadRequest("/panel/task_add_bt_result", ufile);
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeUploadUrlRequest("/panel/task_add_httpftp_result", url);
return new DaemonTaskSuccessResult(task);
case AddByMagnetUrl:
// Request to add a torrent by URL
String magnetUrl = ((AddByMagnetUrlTask)task).getUrl();
makeUploadUrlRequest("/panel/task_add_httpftp_result", magnetUrl);
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
makeRequest("/panel/task_delete", new BasicNameValuePair("id", removeTask.getTargetTorrent().getUniqueID()),
new BasicNameValuePair("action", (removeTask.includingData()? "delete_all": "delete_task")));
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
makeRequest("/panel/task_action", new BasicNameValuePair("id", task.getTargetTorrent().getUniqueID()), new BasicNameValuePair("action", "stop"));
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeRequest("/panel/task_action", new BasicNameValuePair("id", task.getTargetTorrent().getUniqueID()), new BasicNameValuePair("action", "start"));
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Suspend (pause) all active torrents
makeRequest("/panel/tasklist_action", new BasicNameValuePair("id", "suspend_all"));
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume suspended torrents
makeRequest("/panel/tasklist_action", new BasicNameValuePair("id", "resume_all"));
return new DaemonTaskSuccessResult(task);
case StopAll:
// Stop all torrents
makeRequest("/panel/tasklist_action", new BasicNameValuePair("id", "stop_all"));
return new DaemonTaskSuccessResult(task);
case StartAll:
// Start all torrents for download and seeding
makeRequest("/panel/tasklist_action", new BasicNameValuePair("id", "start_all_download"));
makeRequest("/panel/tasklist_action", new BasicNameValuePair("id", "start_all_seeding"));
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
// Request to set the maximum transfer rates
SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
String dl = Integer.toString((ratesTask.getDownloadRate() == null? -1: ratesTask.getDownloadRate().intValue()));
String ul = Integer.toString((ratesTask.getUploadRate() == null? -1: ratesTask.getUploadRate().intValue()));
makeRequest("/panel/option_set", new BasicNameValuePair("key", "down_rate_max"), new BasicNameValuePair("value", dl));
makeRequest("/panel/option_set", new BasicNameValuePair("key", "up_rate_max"), new BasicNameValuePair("value", ul));
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
}
catch (DaemonException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
}
}
/**
* Instantiates an HTTP client with proper credentials that can be used for all Buffalo NAS requests.
* @param connectionTimeout The connection timeout in milliseconds
* @throws DaemonException On conflicting or missing settings
*/
private void initialise(int connectionTimeout) throws DaemonException {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
}
/**
* Build the URL of the HTTP request from the user settings
* @return The URL to request
*/
private String buildWebUIUrl(String path) {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + path;
}
private String makeRequest(String url, NameValuePair... params) throws DaemonException {
try {
// Initialize the HTTP client
if (httpclient == null) {
initialise(HttpHelper.DEFAULT_CONNECTION_TIMEOUT);
}
// Add the parameters to the query string
boolean first = true;
for (NameValuePair param : params) {
if (first) {
url += "?";
first = false;
} else {
url += "&";
}
url += param.getName() + "=" + param.getValue();
}
// Make the request
HttpResponse response = httpclient.execute(new HttpGet(buildWebUIUrl(url)));
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read HTTP response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
// Return raw result
return result;
}
DLog.d(LOG_NAME, "Error: No entity in HTTP response");
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity object in response.");
} catch (UnsupportedEncodingException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private boolean makeFileUploadRequest(String path, String file) throws DaemonException {
try {
// Initialize the HTTP client
if (httpclient == null) {
initialise(HttpHelper.DEFAULT_CONNECTION_TIMEOUT);
}
// Get default download file location first
HttpResponse response = httpclient.execute(new HttpGet(buildWebUIUrl("/panel/task_add_bt")));
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read BitComet response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
int idx = result.indexOf("save_path' value='")+18;
String defaultPath = result.substring(idx, result.indexOf("'>", idx));
// Setup request using POST
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
File upload = new File(URI.create(file));
Part[] parts = { new BitCometFilePart("torrent_file", upload), new Utf8StringPart("save_path", defaultPath) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
// Make the request
response = httpclient.execute(httppost);
entity = response.getEntity();
if (entity != null) {
// Check BitComet response
instream = entity.getContent();
result = HttpHelper.ConvertStreamToString(instream);
instream.close();
if (result.indexOf("failed!") > 0) throw new Exception("Adding torrent file failed");
}
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
return false;
} catch (FileNotFoundException e) {
throw new DaemonException(ExceptionType.FileAccessError, e.toString());
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private boolean makeUploadUrlRequest(String path, String url) throws DaemonException {
try {
// Initialize the HTTP client
if (httpclient == null) {
initialise(HttpHelper.DEFAULT_CONNECTION_TIMEOUT);
}
// Get default download file location first
HttpResponse response = httpclient.execute(new HttpGet(buildWebUIUrl("/panel/task_add_httpftp")));
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read BitComet response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
int idx = result.indexOf("save_path' value='")+18;
String defaultPath = result.substring(idx, result.indexOf("'>", idx));
// Setup form fields and post request
HttpPost httppost = new HttpPost(buildWebUIUrl(path));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("url", url));
params.add(new BasicNameValuePair("save_path", defaultPath));
params.add(new BasicNameValuePair("connection", "5"));
params.add(new BasicNameValuePair("ReferPage", ""));
params.add(new BasicNameValuePair("textSpeedLimit", "0"));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
// Make the request
response = httpclient.execute(httppost);
entity = response.getEntity();
if (entity != null) {
// Check BitComet response
instream = entity.getContent();
result = HttpHelper.ConvertStreamToString(instream);
instream.close();
if (result.indexOf("failed!") > 0) {
throw new Exception("Adding URL failed");
}
}
return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
return false;
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* Parse BitComet HTML page (http response)
* @param response
* @return
* @throws DaemonException
*/
private ArrayList<Torrent> parseHttpTorrents(String response) throws DaemonException {
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
try {
// Find, prepare and split substring with HTML tag TABLE
String[] parts = response.substring(response.indexOf("<TABLE"),response.indexOf("</TABLE>")).replaceAll("</td>", "").replaceAll("</tr>", "").replaceAll("\n", "").split("<tr>");
for (int i=2; i<parts.length; i++) {
String[] subParts = parts[i].replaceAll("<td>", "<td").split("<td");
if (subParts.length == 10 && subParts[1].contains("BT") ) {
String name = subParts[2].substring(subParts[2].indexOf("/panel/task_detail"));
name = name.substring(name.indexOf(">")+1, name.indexOf("<"));
TorrentStatus status = convertStatus(subParts[3]);
String percenDoneStr = subParts[6];
String downloadRateStr = subParts[7];
String uploadRateStr = subParts[8];
long size = convertSize(subParts[5]);
float percentDone = Float.parseFloat(percenDoneStr.substring(0, percenDoneStr.indexOf("%")));
long sizeDone = (long) (size * percentDone / 100 );
int rateUp = 1000 * Integer.parseInt(uploadRateStr.substring(0, uploadRateStr.indexOf("kB/s")));
int rateDown = 1000 * Integer.parseInt(downloadRateStr.substring(0, downloadRateStr.indexOf("kB/s")));
// Unfortunately, there is no info for above values providing by BitComet now,
// so we may only send additional request for that
int leechers = 0;
int seeders = 0;
int knownLeechers = 0;
int knownSeeders = 0;
int distributed_copies = 0;
long sizeUp = 0;
String comment = "";
Date dateAdded = new Date();
// Comment code below to speedup torrent listing
// P.S. feature request to extend torrents info is already sent to the BitComet developers
//*
try {
// Lets make summary request and parse details
String summary = makeRequest("/panel/task_detail", new BasicNameValuePair("id", ""+(i-2)), new BasicNameValuePair("show", "summary"));
String[] sumParts = summary.substring(summary.indexOf("<div align=\"left\">Value</div></th>")).split("<tr><td>");
comment = sumParts[7].substring(sumParts[7].indexOf("<td>")+4, sumParts[7].indexOf("</td></tr>"));
// Indexes for date and uploaded size
int idx = 9;
int sizeIdx = 12;
if (status == TorrentStatus.Downloading) {
seeders = Integer.parseInt(sumParts[9].substring(sumParts[9].indexOf("Seeds:")+6, sumParts[9].indexOf("(Max possible")));
leechers = Integer.parseInt(sumParts[9].substring(sumParts[9].indexOf("Peers:")+6, sumParts[9].lastIndexOf("(Max possible")));
knownSeeders = Integer.parseInt(sumParts[9].substring(sumParts[9].indexOf("(Max possible:")+14, sumParts[9].indexOf(")")));
knownLeechers = Integer.parseInt(sumParts[9].substring(sumParts[9].lastIndexOf("(Max possible:")+14, sumParts[9].lastIndexOf(")")));
idx = 13;
sizeIdx = 16;
}
DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss");
dateAdded = df.parse(sumParts[idx].substring(sumParts[idx].indexOf("<td>")+4, sumParts[idx].indexOf("</td></tr>")));
//sizeDone = convertSize(sumParts[sizeIdx].substring(sumParts[sizeIdx].indexOf("<td>")+4, sumParts[sizeIdx].indexOf(" (")));
sizeUp = convertSize(sumParts[sizeIdx+1].substring(sumParts[sizeIdx+1].indexOf("<td>")+4, sumParts[sizeIdx+1].indexOf(" (")));
}
catch (Exception e) {}
//*
// Add the parsed torrent to the list
torrents.add(new Torrent(
(long)i-2,
null,
name,
status,
null,
rateDown,
rateUp,
leechers,
seeders,
knownLeechers,
knownSeeders,
(rateDown == 0? -1: (int) ((size - sizeDone) / rateDown)),
sizeDone,
sizeUp,
size,
percentDone / 100,
distributed_copies,
comment,
dateAdded,
null,
null));
}
}
}
catch (Exception e) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Invalid BitComet HTTP response.");
}
return torrents;
}
/**
* Parse BitComet AJAX response
* that code was copy-pasted and slightly modified from \Ktorrent\StatsParser.java
* @param response
* @return
* @throws DaemonException
*/
private ArrayList<Torrent> parseXmlTorrents(String response) throws DaemonException {
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
try {
// Use a PullParser to handle XML tags one by one
XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser();
xpp.setInput(new StringReader(response));
// Temp variables to load into torrent objects
int id = 0;
String name = "";
@SuppressWarnings("unused")
String hash = "";
TorrentStatus status = TorrentStatus.Unknown;
long sizeDone = 0;
long sizeUp = 0;
long totalSize = 0;
int rateDown = 0;
int rateUp = 0;
int seeders = 0;
int seedersTotal = 0;
int leechers = 0;
int leechersTotal = 0;
float progress = 0;
String label = "";
Date dateAdded = new Date();
// Start pulling
int next = xpp.nextTag();
String tagName = xpp.getName();
while (next != XmlPullParser.END_DOCUMENT) {
if (next == XmlPullParser.END_TAG && tagName.equals("task")) {
// End of a 'transfer' item, add gathered torrent data
sizeDone = (long) (totalSize * progress);
torrents.add(new Torrent(
id,
null, // hash, // we suppose to use simple integer IDs
name,
status,
null,
rateDown,
rateUp,
leechers,
seeders,
seeders + leechers,
seedersTotal + leechersTotal,
(int) ((status == TorrentStatus.Downloading && rateDown != 0)? (totalSize - sizeDone) / rateDown: -1), // eta (in seconds) = (total_size_in_btes - bytes_already_downloaded) / bytes_per_second
sizeDone,
sizeUp,
totalSize,
progress,
0f,
label,
dateAdded,
null,
null)); // Not supported in the web interface
id++; // Stop/start/etc. requests are made by ID, which is the order number in the returned XML list :-S
} else if (next == XmlPullParser.START_TAG && tagName.equals("task")){
// Start of a new 'transfer' item; reset gathered torrent data
name = "";
//hash = "";
status = TorrentStatus.Unknown;
sizeDone = 0;
sizeUp = 0;
totalSize = 0;
rateDown = 0;
rateUp = 0;
seeders = 0;
seedersTotal = 0;
leechers = 0;
leechersTotal = 0;
progress = 0;
label = "";
dateAdded = new Date();
} else if (next == XmlPullParser.START_TAG){
// Probably encountered a torrent property, i.e. '<type>BT</type>'
next = xpp.next();
if (next == XmlPullParser.TEXT) {
if (tagName.equals("name")) {
name = xpp.getText().trim();
} else if (tagName.equals("infohash")) {
hash = xpp.getText().trim();
} else if (tagName.equals("state")) {
status = convertStatus(xpp.getText());
} else if (tagName.equals("bytes_downloaded")) {
sizeDone = Integer.parseInt(xpp.getText());
} else if (tagName.equals("bytes_uploaded")) {
sizeUp = Integer.parseInt(xpp.getText());
} else if (tagName.equals("size")) {
totalSize = Long.parseLong(xpp.getText());
} else if (tagName.equals("down_speed")) {
rateDown = Integer.parseInt(xpp.getText());
} else if (tagName.equals("up_speed")) {
rateUp = Integer.parseInt(xpp.getText());
} else if (tagName.equals("seeders")) {
seeders = Integer.parseInt(xpp.getText());
} else if (tagName.equals("total_seeders")) {
seedersTotal = Integer.parseInt(xpp.getText());
} else if (tagName.equals("peers")) {
leechers = Integer.parseInt(xpp.getText());
} else if (tagName.equals("total_peers")) {
leechersTotal = Integer.parseInt(xpp.getText());
} else if (tagName.equals("progress_permillage")) {
progress = convertProgress(xpp.getText());
} else if (tagName.equals("created_time")) {
dateAdded = new Date(Long.parseLong(xpp.getText()));
} else if (tagName.equals("comment")) {
label = xpp.getText().trim();
}
}
}
next = xpp.next();
if (next == XmlPullParser.START_TAG || next == XmlPullParser.END_TAG) {
tagName = xpp.getName();
}
}
} catch (XmlPullParserException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (Exception e) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Invalid BitComet HTTP response.");
}
return torrents;
}
/**
* Parse BitComet HTML page (HTTP response)
* @param response
* @return
* @throws DaemonException
*/
private ArrayList<TorrentFile> parseHttpTorrentFiles(String response, String hash) throws DaemonException {
// Parse response
ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
try {
String[] files = response.substring(response.indexOf("Operation Method</div></th>")+27, response.lastIndexOf("</TABLE>")).replaceAll("</td>", "").replaceAll("</tr>", "").split("<tr>");
for (int i = 1; i < files.length; i++) {
String[] fileDetails = files[i].replace(">","").split("<td");
long size = convertSize(fileDetails[4].substring(fileDetails[4].indexOf("   ")+11));
long sizeDone = 0;
if (!fileDetails[2].contains("--")) {
double percentDone = Double.parseDouble(fileDetails[2].substring(0, fileDetails[2].indexOf("%")));
sizeDone = (long) ( size / 100.0 * percentDone);
}
torrentfiles.add(new TorrentFile(
hash,
fileDetails[3],
fileDetails[3],
settings.getDownloadDir() + fileDetails[3],
size,
sizeDone,
convertPriority(fileDetails[1])));
}
}
catch (Exception e) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Invalid BitComet HTTP response.");
}
// Return the list
return torrentfiles;
}
/**
* Returns the size of the torrent, as parsed form some string
* @param size The size in a string format, i.e. '691 MB'
* @return The size in bytes
*/
private static long convertSize(String size) {
try {
if (size.endsWith("GB")) {
return (long)(Float.parseFloat(size.substring(0, size.indexOf("GB"))) * 1024 * 1024 * 1024);
} else if (size.endsWith("MB")) {
return (long)(Float.parseFloat(size.substring(0, size.indexOf("MB"))) * 1024 * 1024);
} else if (size.endsWith("kB")) {
return (long)(Float.parseFloat(size.substring(0, size.indexOf("kB"))) * 1024);
} else if (size.endsWith("B")) {
return (long)(Float.parseFloat(size.substring(0, size.indexOf("B"))));
}
}
catch (Exception e) { }
return 0;
}
/**
* Parse BitComet torrent files priority
**/
private Priority convertPriority(String priority) {
if (priority.equals("Very High") || priority.equals("High")) {
return Priority.High;
} else if (priority.equals("Normal")) {
return Priority.Normal;
}
return Priority.Off;
}
/**
* Parse BitComet torrent status
**/
private TorrentStatus convertStatus(String state) {
// Status is given as a descriptive string and an indication if the torrent was stopped/paused
if (state.equals("stopped")) {
return TorrentStatus.Paused;
} else if (state.equals("running")) {
return TorrentStatus.Downloading;
}
return TorrentStatus.Unknown;
}
/**
* Returns the part done (or progress) of a torrent, as parsed from some string
* @param progress The part done in a string format, i.e. '15.96'
* @return The part done as [0..1] fraction, i.e. 0.1596
*/
public static float convertProgress(String progress) {
return Float.parseFloat(progress) / 1000.0f;
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
package org.transdroid.daemon;
public enum OS {
Windows {
@Override public String getPathSeperator() { return "\\"; }
},
Mac {
@Override public String getPathSeperator() { return "/"; }
},
Linux {
@Override public String getPathSeperator() { return "/"; }
};
public static OS fromCode(String osCode) {
if (osCode == null) {
return null;
}
if (osCode.equals("type_windows")) {
return Windows;
}
if (osCode.equals("type_mac")) {
return Mac;
}
if (osCode.equals("type_linux")) {
return Linux;
}
return null;
}
public abstract String getPathSeperator();
}
| Java |
package org.transdroid.daemon.Ktorrent;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* A Ktorrent-specific parser for it's /data/torrent/files.xml output.
*
* @author erickok
*
*/
public class FileListParser {
public static List<TorrentFile> parse(Reader in, String torrentDownloadDir) throws DaemonException, LoggedOutException {
try {
// Use a PullParser to handle XML tags one by one
XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser();
xpp.setInput(in);
// Temp variables to load into torrent objects
int i = 0;
String path = "";
long size = 0;
float partDone = 0;
Priority priority = Priority.Normal;
// Start pulling
List<TorrentFile> torrents = new ArrayList<TorrentFile>();
int next = xpp.nextTag();
String name = xpp.getName();
// Check if we had a proper XML result
if (name.equals("html")) {
// Apparently we were returned an HTML page instead of the expected XML
// This happens in particular when we were logged out (because somebody else logged into KTorrent's web interface)
throw new LoggedOutException();
}
while (next != XmlPullParser.END_DOCUMENT) {
if (next == XmlPullParser.END_TAG && name.equals("file")) {
// End of a 'transfer' item, add gathered torrent data
torrents.add(new TorrentFile(
"" + i,
path,
path,
(torrentDownloadDir == null? null: torrentDownloadDir + path),
size,
(long) (size * partDone),
priority));
} else if (next == XmlPullParser.START_TAG && name.equals("file")){
// Start of a new 'transfer' item; reset gathered torrent data
i++; // Increase the file index identifier
path = "";
size = 0;
partDone = 0;
priority = Priority.Normal;
} else if (next == XmlPullParser.START_TAG){
// Probably encountered a file property, i.e. '<percentage>73.09</percentage>'
next = xpp.next();
if (next == XmlPullParser.TEXT) {
if (name.equals("path")) {
path = xpp.getText().trim();
} else if (name.equals("size")) {
size = StatsParser.convertSize(xpp.getText());
} else if (name.equals("priority")) {
priority = convertPriority(xpp.getText());
} else if (name.equals("percentage")) {
partDone = StatsParser.convertProgress(xpp.getText());
}
}
}
next = xpp.next();
if (next == XmlPullParser.START_TAG || next == XmlPullParser.END_TAG) {
name = xpp.getName();
}
}
return torrents;
} catch (XmlPullParserException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (IOException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* Returns the priority of a file, as parsed from some string
* @param priority The priority in a numeric string, i.e. '20'
* @return The priority as enum type, i.e. Priority.Off
*/
private static Priority convertPriority(String priority) {
if (priority.equals("20")) {
return Priority.Off;
} else if (priority.equals("30")) {
return Priority.Low;
} else if (priority.equals("50")) {
return Priority.High;
} else {
return Priority.Normal;
}
}
}
| Java |
package org.transdroid.daemon.Ktorrent;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* A Ktorrent-specific parser for it's /data/torrents.xml output.
*
* @author erickok
*
*/
public class StatsParser {
public static List<Torrent> parse(Reader in, String baseDir, String pathSeperator) throws DaemonException, LoggedOutException {
try {
// Use a PullParser to handle XML tags one by one
XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser();
xpp.setInput(in);
//xpp.setInput(new FileReader("/sdcard/torrents.xml")); // Used for debugging
// Temp variables to load into torrent objects
int id = 0;
String tname = "";
//String hash = "";
TorrentStatus status = TorrentStatus.Unknown;
long down = 0;
long up = 0;
long total = 0;
int downRate = 0;
int upRate = 0;
int seeders = 0;
int seedersTotal = 0;
int leechers = 0;
int leechersTotal = 0;
float progress = 0;
int numFiles = -1;
// Start pulling
List<Torrent> torrents = new ArrayList<Torrent>();
int next = xpp.nextTag();
String name = xpp.getName();
// Check if we had a proper XML result
if (name.equals("html")) {
// Apparently we were returned an HTML page instead of the expected XML
// This happens in particular when we were logged out (because somebody else logged into KTorrent's web interface)
throw new LoggedOutException();
}
while (next != XmlPullParser.END_DOCUMENT) {
if (next == XmlPullParser.END_TAG && name.equals("torrent")) {
// End of a 'transfer' item, add gathered torrent data
torrents.add(new Torrent(
id,
""+id,
tname,
status,
(baseDir == null? null: (numFiles > 0? baseDir + tname + pathSeperator: baseDir)),
downRate,
upRate,
leechers,
seeders,
seeders + leechers,
seedersTotal + leechersTotal,
(int) (status == TorrentStatus.Downloading? (total - down) / downRate: -1), // eta (in seconds) = (total_size_in_btes - bytes_already_downloaded) / bytes_per_second
down,
up,
total,
progress,
0f,
null, // Not supported in the web interface
null, // Not supported in the web interface
null, // Not supported in the web interface
null)); // Not supported in the web interface
id++; // Stop/start/etc. requests are made by ID, which is the order number in the returned XML list :-S
} else if (next == XmlPullParser.START_TAG && name.equals("torrent")){
// Start of a new 'transfer' item; reset gathered torrent data
tname = "";
//hash = "";
status = TorrentStatus.Unknown;
down = 0;
up = 0;
total = 0;
downRate = 0;
upRate = 0;
seeders = 0;
seedersTotal = 0;
leechers = 0;
leechersTotal = 0;
progress = 0;
numFiles = -1;
} else if (next == XmlPullParser.START_TAG){
// Probably encountered a torrent property, i.e. '<status>Stopped</status>'
next = xpp.next();
if (next == XmlPullParser.TEXT) {
if (name.equals("name")) {
tname = xpp.getText().trim();
//} else if (name.equals("info_hash")) {
//hash = xpp.getText().trim();
} else if (name.equals("status")) {
status = convertStatus(xpp.getText());
} else if (name.equals("bytes_downloaded")) {
down = convertSize(xpp.getText());
} else if (name.equals("bytes_uploaded")) {
up = convertSize(xpp.getText());
} else if (name.equals("total_bytes_to_download")) {
total = convertSize(xpp.getText());
} else if (name.equals("download_rate")) {
downRate = convertRate(xpp.getText());
} else if (name.equals("upload_rate")) {
upRate = convertRate(xpp.getText());
} else if (name.equals("seeders")) {
seeders = Integer.parseInt(xpp.getText());
} else if (name.equals("seeders_total")) {
seedersTotal = Integer.parseInt(xpp.getText());
} else if (name.equals("leechers")) {
leechers = Integer.parseInt(xpp.getText());
} else if (name.equals("leechers_total")) {
leechersTotal = Integer.parseInt(xpp.getText());
} else if (name.equals("percentage")) {
progress = convertProgress(xpp.getText());
} else if (name.equals("num_files")) {
numFiles = Integer.parseInt(xpp.getText());
}
}
}
next = xpp.next();
if (next == XmlPullParser.START_TAG || next == XmlPullParser.END_TAG) {
name = xpp.getName();
}
}
return torrents;
} catch (XmlPullParserException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (IOException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* Returns the part done (or progress) of a torrent, as parsed from some string
* @param progress The part done in a string format, i.e. '15.96'
* @return The part done as [0..1] fraction, i.e. 0.1596
*/
public static float convertProgress(String progress) {
return Float.parseFloat(progress) / 100;
}
/**
* Parses a KTorrent-style number string into a float value
* @param numberString A formatted number string without any letter (like GiB)
* @return The corresponding float value
*/
private static Float convertStringToFloat(String numberString) {
// KTorrent has issues with formatting its numeric values as strings. It does not always
// adhere to the localization and never indicates which formatting it will use. We therefore
// have to assume an American style format unless we have indications to assume otherwise.
int comma = numberString.indexOf(',');
int dot = numberString.indexOf('.');
if (comma > 0 && dot > 0) {
if (comma < dot) {
// Like 1,234.5
return Float.parseFloat(numberString.replace(",", ""));
} else {
// Like 1.234,5
return Float.parseFloat(numberString.replace(".", "").replace(",", "."));
}
} else {
if (comma > 0) {
// Like 234,5
return Float.parseFloat(numberString.replace(",", "."));
} else {
// Like 234.5
return Float.parseFloat(numberString);
}
}
}
/**
* Returns the size of the torrent, as parsed form some string
* @param size The size in a string format, e.g. '1,011.7 MiB'
* @return The size in number of kB
*/
public static long convertSize(String size) {
if (size.endsWith("GiB")) {
return (long)(convertStringToFloat(size.substring(0, size.length() - 4)) * 1024 * 1024 * 1024);
} else if (size.endsWith("MiB")) {
return (long)(convertStringToFloat(size.substring(0, size.length() - 4)) * 1024 * 1024);
} else if (size.endsWith("KiB")) {
return (long)(convertStringToFloat(size.substring(0, size.length() - 4)) * 1024);
} else if (size.endsWith("B")) {
return convertStringToFloat(size.substring(0, size.length() - 2)).longValue();
}
return 0;
}
/**
* Returns the rate (speed), as parsed from some string
* @param rate The rate in a string format,e.g. '9.2 KiB/s'
* @return The rate (or speed) in KiB/s
*/
public static int convertRate(String rate) {
if (rate.endsWith("MiB/s")) {
return (int) (convertStringToFloat(rate.substring(0, rate.length() - 6)) * 1024 * 1024);
} else if (rate.endsWith("KiB/s")) {
return (int) (convertStringToFloat(rate.substring(0, rate.length() - 6)) * 1024);
} else if (rate.endsWith("B/s")) {
return convertStringToFloat(rate.substring(0, rate.length() - 4)).intValue();
}
return 0;
}
/**
* Returns the status, as parsed from some string
* @param status THe torrent status in a string format, i.e. 'Leeching'
* @return The status as TorrentStatus or Unknown if it could not been parsed
*/
private static TorrentStatus convertStatus(String status) {
if (status.equals("Downloading")) {
return TorrentStatus.Downloading;
} else if (status.equals("Seeding")) {
return TorrentStatus.Seeding;
} else if (status.equals("Stopped")) {
return TorrentStatus.Paused;
} else if (status.equals("Stalled")) {
return TorrentStatus.Paused;
} else if (status.equals("Download completed")) {
return TorrentStatus.Paused;
} else if (status.equals("Not started")) {
return TorrentStatus.Paused;
} else if (status.equals("Stalled")) {
return TorrentStatus.Waiting;
} else if (status.equals("Checking data")) {
return TorrentStatus.Checking;
}
return TorrentStatus.Unknown;
}
}
| Java |
package org.transdroid.daemon.Ktorrent;
public class LoggedOutException extends Exception {
private static final long serialVersionUID = 1L;
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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 org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.client.RedirectHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
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.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
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;
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.GetFileListTask;
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;
/**
* 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 {
private static final String LOG_NAME = "Ktorrent daemon";
private static final String RPC_URL_CHALLENGE = "/login/challenge.xml";
private static final String RPC_URL_LOGIN = "/login?page=interface.html";
private static final String RPC_URL_LOGIN_USER = "username";
private static final String RPC_URL_LOGIN_PASS = "password";
private static final String RPC_URL_LOGIN_CHAL = "challenge";
private static final String RPC_URL_STATS = "/data/torrents.xml?L10n=no";
private static final String RPC_URL_ACTION = "/action?";
private static final String RPC_URL_UPLOAD = "/torrent/load?page=interface.html";
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 = "<result>OK</result>";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
static private int retries = 0;
/**
* Initialises an adapter that provides operations to the Ktorrent web interface
*/
public KtorrentAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(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:
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()));
}
} 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);
} 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"));
}
} catch (DaemonException e) {
// Invalidate our session
httpclient = null;
// Return the task failure
return new DaemonTaskFailureResult(task, e);
}
}
private List<Torrent> makeStatsRequest() throws DaemonException, LoggedOutException {
try {
// Initialise the HTTP client
initialise();
makeLoginRequest();
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + RPC_URL_STATS);
HttpResponse response = httpclient.execute(httpget);
// Read XML response
InputStream instream = response.getEntity().getContent();
List<Torrent> torrents = StatsParser.parse(new InputStreamReader(instream), settings.getDownloadDir(), settings.getOS().getPathSeperator());
instream.close();
return torrents;
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
DLog.d(LOG_NAME, "Parsing error: " + e.toString());
throw e;
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private List<TorrentFile> makeFileListRequest(Torrent torrent) throws DaemonException, LoggedOutException {
try {
// Initialise the HTTP client
initialise();
makeLoginRequest();
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + RPC_URL_FILES + torrent.getUniqueID());
HttpResponse response = httpclient.execute(httpget);
// Read XML response
InputStream instream = response.getEntity().getContent();
List<TorrentFile> 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;
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
DLog.d(LOG_NAME, "Parsing error: " + e.toString());
throw e;
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private void makeLoginRequest() throws DaemonException {
try {
// Make challenge request
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();
instream.close();
// Challenge string should be something like TncpX3TB8uZ0h8eqztZ6
if (challengeString == null || challengeString.length() != 20) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No (valid) challenge string received");
}
// Make login request
HttpPost httppost2 = new HttpPost(buildWebUIUrl() + RPC_URL_LOGIN);
List<NameValuePair> params = new ArrayList<NameValuePair>(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
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());
throw e;
} catch (Exception e) {
DLog.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 {
try {
// Initialise the HTTP client
initialise();
makeLoginRequest();
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + RPC_URL_ACTION + action);
HttpResponse response = httpclient.execute(httpget);
// Read response (a successful action always returned '1')
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
if (result.contains(RPC_SUCCESS)) {
return true;
} else if (result.contains("KTorrent WebInterface - Login")) {
// Apparently we were returned an HTML page instead of the expected XML
// This happens in particular when we were logged out (because somebody else logged into KTorrent's web interface)
throw new LoggedOutException();
} else {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Action response was not OK but " + result);
}
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
DLog.d(LOG_NAME, action + " request error: " + e.toString());
throw e;
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private boolean makeFileUploadRequest(String target) throws DaemonException, LoggedOutException {
try {
// Initialise the HTTP client
initialise();
makeLoginRequest();
// Make request
HttpPost httppost = new HttpPost(buildWebUIUrl() + RPC_URL_UPLOAD);
File upload = new File(URI.create(target));
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; }
@Override
public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException { return null; }
};
httpclient.setRedirectHandler(handler);
HttpResponse response = httpclient.execute(httppost);
// Read response (a successful action always returned '1')
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
if (result.equals("")) {
return true;
} else if (result.contains("KTorrent WebInterface - Login")) {
// Apparently we were returned an HTML page instead of the expected XML
// This happens in particular when we were logged out (because somebody else logged into KTorrent's web interface)
throw new LoggedOutException();
} else {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Action response was not 1 but " + result);
}
} catch (LoggedOutException e) {
throw e;
} catch (DaemonException e) {
DLog.d(LOG_NAME, "File upload error: " + e.toString());
throw e;
} catch (Exception e) {
DLog.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
*/
/*private boolean authenticated() {
// We should have a Ktorrent cookie in the httpclient when we are authenticated
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if (cookie.getName().equals(RPC_COOKIE_NAME)) {
return true;
}
}
return false;
}*/
/**
* 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 {
if (httpclient != null) {
httpclient = null;
}
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
*/
private String buildWebUIUrl() {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort();
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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 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.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.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.Label;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
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.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;
/**
* 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 DaemonSettings settings;
private DefaultHttpClient httpclient;
private String authtoken;
/**
* Initialises an adapter that provides operations to the uTorrent web daemon
*/
public UtorrentAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(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);
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()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} 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()));
} 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<Label> parseJsonRetrieveGetLabels(JSONArray lresults) throws JSONException {
// Parse response
ArrayList<Label> labels = new ArrayList<Label>();
for (int i = 0; i < lresults.length(); i++) {
JSONArray lab = lresults.getJSONArray(i);
String name = lab.getString(NAME_IDX);
int count = lab.getInt(COUNT_IDX);
labels.add(new Label(
name,
count
));
}
return labels;
}
private JSONObject makeUtorrentRequest(String addToUrl) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
ensureToken();
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl() + "?token=" + authtoken + addToUrl);
HttpResponse response = httpclient.execute(httpget);
// Read JSON response
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
if ((result.equals("") || result.trim().equals("invalid request"))) {
authtoken = null;
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;
} catch (DaemonException e) {
throw e;
} catch (JSONException e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private void ensureToken() throws IOException, ClientProtocolException, DaemonException {
// Make sure we have a valid token
if (authtoken == null) {
// Make a request to /gui/token.html
// See http://trac.utorrent.com/trac/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");
}
if (response.getStatusLine().getStatusCode() == 404) {
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();
}
}
public JSONObject uploadTorrentFile(String file) throws DaemonException, ClientProtocolException, 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) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
HttpResponse response = httpclient.execute(httppost);
// Read JSON response
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
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/";
}
private TorrentStatus convertUtorrentStatus(int uStatus, boolean finished) {
// Convert bitwise int to uTorrent status codes
// Now based on http://forum.utorrent.com/viewtopic.php?id=50779
if ((uStatus & 1) == 1) {
// Started
if ((uStatus & 32) == 32) {
// Paused
return TorrentStatus.Paused;
} else if (finished) {
return TorrentStatus.Seeding;
} else {
return TorrentStatus.Downloading;
}
} else if ((uStatus & 2) == 2) {
// Checking
return TorrentStatus.Checking;
} else if ((uStatus & 16) == 16) {
// Error
return TorrentStatus.Error;
} else if ((uStatus & 128) == 128) {
// Queued
return TorrentStatus.Queued;
} else {
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;
}
}
private int convertPriority(Priority newPriority) {
if (newPriority == null) {
return 2;
}
switch (newPriority) {
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<Torrent> parseJsonRetrieveTorrents(JSONArray results) throws JSONException {
// Parse response
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
boolean createPaths = !(settings.getDownloadDir() == null || settings.getDownloadDir().equals(""));
for (int i = 0; i < results.length(); i++) {
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
// 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;
if (createPaths) {
dir = settings.getDownloadDir();
if (name.length() < 4 || name.charAt(name.length() - 4) != '.') {
// Assume this is a directory rather than a single-file torrent
dir += name + settings.getOS().getPathSeperator();
}
}
// Add the parsed torrent to the list
TorrentStatus status = convertUtorrentStatus(tor.getInt(RPC_STATUS_IDX), downloaded);
long addedOn = tor.optInt(RPC_ADDEDON_IDX, -1) * 1000L;
long completedOn = tor.optInt(RPC_COMPLETEDON_IDX, -1) * 100L;
Date addedOnDate = addedOn == -1? null: new Date(addedOn);
Date completedOnDate = completedOn == -1? null: new Date(completedOn);
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_PEERSCONNECTED_IDX),
(downloaded? tor.getInt(RPC_SEEDSINSWARM_IDX): tor.getInt(RPC_PEERSINSWARM_IDX)),
0, // Not available
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,
// uTorrent doesn't give the error message, so just remind that there is some error
status == TorrentStatus.Error? "See GUI for error message": null));
}
return torrents;
}
private TorrentDetails parseJsonTorrentDetails(JSONArray results) throws JSONException {
// Parse response
// NOTE: Assumes only details for one torrent are requested at a time
if (results.length() > 0) {
JSONObject tor = results.getJSONObject(0);
List<String> trackers = new ArrayList<String>();
for (String tracker : tor.getString("trackers").split("\\r\\n")) {
// Ignore any blank lines
if (!tracker.trim().equals("")) {
trackers.add(tracker.trim());
}
}
// uTorrent doesn't support tracker error messages in the web UI
// 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<TorrentFile> parseJsonFileListing(JSONArray results, Torrent torrent) throws JSONException {
// Parse response
ArrayList<TorrentFile> files = new ArrayList<TorrentFile>();
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
}
return files;
}
private String getAllHashes() throws DaemonException, JSONException {
// Make a retrieve torrents call first to gather all hashes
JSONObject result = makeUtorrentRequest("&list=1");
ArrayList<Torrent> 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
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
package org.transdroid.daemon.Tfb4rt;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* A Torrentflux-b4rt-specific parser for it's stats.xml output.
*
* @author erickok
*
*/
public class StatsParser {
public static List<Torrent> parse(Reader in) throws DaemonException {
try {
// Use a PullParser to handle XML tags one by one
XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser();
//in = new FileReader("/sdcard/tfdebug.xml");
xpp.setInput(in);
// Temp variables to load into torrent objects
int id = 0;
String tname = "";
int time = 0; // Seconds remaining
int up = 0; // Upload rate in seconds
int down = 0; // Download rate in seconds
float progress = 0; // Part [0,1] completed
TorrentStatus status = TorrentStatus.Unknown;
long size = 0; // Total size
long upSize = -1; // Total uploaded
// Start pulling
List<Torrent> torrents = new ArrayList<Torrent>();
int next = xpp.nextTag();
String name = xpp.getName();
if (name.equals("html")) {
// We are given an html page instead of xml data; probably an authentication error
throw new DaemonException(DaemonException.ExceptionType.AuthenticationFailure, "HTML tag found instead of XML data; authentication error?");
}
if (name.equals("rss")) {
// We are given an html page instead of xml data; probably an authentication error
throw new DaemonException(DaemonException.ExceptionType.UnexpectedResponse, "RSS feed found instead of XML data; configuration error?");
}
while (next != XmlPullParser.END_DOCUMENT) {
if (next == XmlPullParser.END_TAG && name.equals("transfer")) {
// End of a 'transfer' item, add gathered torrent data
torrents.add(new Torrent(
id++,
tname,
tname,
status,
null,
down,
up,
0,
0,
0,
0,
time,
(progress > 1L? size: (long)(progress * size)), // Cap the download size to the torrent size
(upSize == -1? (progress > 1L? (long)(progress * size): 0L): upSize), // If T. Up doesn't exist, we can use the progress size instead
size,
(status == TorrentStatus.Seeding? 1F: progress),
0f,
null, // Not supported in the XML stats
null,
null,
null));
} else if (next == XmlPullParser.START_TAG && name.equals("transfer")){
// Start of a new 'transfer' item, for which the name is in the first attribute
// i.e. '<transfer name="_isoHunt_ubuntu-9.10-desktop-amd64.iso.torrent">'
tname = xpp.getAttributeValue(0);
// Reset gathered torrent data
size = 0;
status = TorrentStatus.Unknown;
progress = 0;
down = 0;
up = 0;
time = 0;
} else if (next == XmlPullParser.START_TAG && name.equals("transferStat")){
// Encountered an actual stat, which will always have an attribute name indicating it's type
// i.e. '<transferStat name="Size">691 MB</transferStat>'
String type = xpp.getAttributeValue(0);
next = xpp.next();
if (next == XmlPullParser.TEXT) {
try {
if (type.equals("Size")) {
size = convertSize(xpp.getText());
} else if (type.equals("Status")) {
status = convertStatus(xpp.getText());
} else if (type.equals("Progress")) {
progress = convertProgress(xpp.getText());
} else if (type.equals("Down")) {
down = convertRate(xpp.getText());
} else if (type.equals("Up")) {
up = convertRate(xpp.getText());
} else if (type.equals("Estimated Time")) {
time = convertEta(xpp.getText());
} else if (type.equals("T. Up")) {
upSize = convertSize(xpp.getText());
}
} catch (Exception e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
}
next = xpp.next();
if (next == XmlPullParser.START_TAG || next == XmlPullParser.END_TAG) {
name = xpp.getName();
}
}
return torrents;
} catch (XmlPullParserException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (IOException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* Returns the part done (or progress) of a torrent, as parsed from some string
* @param progress The part done in a string format, i.e. '15%'
* @return The part done as [0..1] fraction
*/
private static float convertProgress(String progress) {
if (progress.endsWith("%")) {
return Float.parseFloat(progress.substring(0, progress.length() - 1).replace(",", "")) / 100;
}
return 0;
}
/**
* Returns the size of the torrent, as parsed form some string
* @param size The size in a string format, i.e. '691 MB'
* @return The size in number of kB
*/
private static long convertSize(String size) {
if (size.endsWith("GB")) {
return (long)(Float.parseFloat(size.substring(0, size.length() - 3)) * 1024 * 1024 * 1024);
} else if (size.endsWith("MB")) {
return (long)(Float.parseFloat(size.substring(0, size.length() - 3)) * 1024 * 1024);
} else if (size.endsWith("kB")) {
return (long)(Float.parseFloat(size.substring(0, size.length() - 3)) * 1024);
} else if (size.endsWith("B")) {
return (long)(Float.parseFloat(size.substring(0, size.length() - 2)));
}
return 0;
}
/**
* Returns the eta (estimated time of arrival), as parsed from some string
* @param time The time in a string format, i.e. '1d 06:20:48' or '21:36:49'
* @return The eta in number of seconds
*/
private static int convertEta(String time) {
if (!time.contains(":")) {
// Not running (something like 'Torrent Stopped' is shown)
return -1;
}
int seconds = 0;
// Days
if (time.contains("d ")) {
seconds += Integer.parseInt(time.substring(0, time.indexOf("d "))) * 60 * 60 * 24;
time = time.substring(time.indexOf("d ") + 2);
}
// Hours, minutes and seconds
String[] parts = time.split(":");
if (parts.length > 2) {
seconds += Integer.parseInt(parts[0]) * 60 * 60;
seconds += Integer.parseInt(parts[1]) * 60;
seconds += Integer.parseInt(parts[2]);
} else if (parts.length > 1) {
seconds += Integer.parseInt(parts[0]) * 60;
seconds += Integer.parseInt(parts[1]);
} else {
seconds += Integer.parseInt(time);
}
return seconds;
}
/**
* Returns the rate (speed), as parsed from some string
* @param rate The rate in a string format, i.e. '9 kB/s'
* @return The rate (or speed) in kB/s
*/
private static int convertRate(String rate) {
if (rate.endsWith("MB/s")) {
return (int) (Float.parseFloat(rate.substring(0, rate.length() - 5)) * 1024 * 1024);
} else if (rate.endsWith("kB/s")) {
return (int) (Float.parseFloat(rate.substring(0, rate.length() - 5)) * 1024);
} else if (rate.endsWith("B/s")) {
return (int) Float.parseFloat(rate.substring(0, rate.length() - 4));
}
return 0;
}
/**
* Returns the status, as parsed from some string
* @param status THe torrent status in a string format, i.e. 'Leeching'
* @return The status as TorrentStatus or Unknown if it could not been parsed
*/
private static TorrentStatus convertStatus(String status) {
if (status.equals("Leeching")) {
return TorrentStatus.Downloading;
} else if (status.equals("Seeding")) {
return TorrentStatus.Seeding;
} else if (status.equals("Stopped")) {
return TorrentStatus.Paused;
} else if (status.equals("New")) {
return TorrentStatus.Paused;
} else if (status.equals("Done")) {
return TorrentStatus.Paused;
}
return TorrentStatus.Unknown;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.Tfb4rt;
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.List;
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.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.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;
import com.android.internalcopy.http.multipart.Part;
/**
* An adapter that allows for easy access to Torrentflux-b4rt installs. Communication
* is handled via HTTP GET requests and XML responses.
*
* @author erickok
*
*/
public class Tfb4rtAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "Torrentflux-b4rt daemon";
private static final String RPC_URL_STATS = "/stats.php?t=all&f=xml";
private static final String RPC_URL_DISPATCH = "/dispatcher.php?action=";
private static final String RPC_URL_DISPATCH2 = "&riid=_exit_";
private static final String RPC_URL_TRANSFER = "&transfer=";
private static final String RPC_URL_AID = "&aid=2";
private static final String RPC_URL_URL = "&url=";
private static final String RPC_URL_USER = "&username=";
private static final String RPC_URL_PASS = "&md5pass=";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
/**
* Initialises an adapter that provides operations to the Torrentflux-b4rt pages
*/
public Tfb4rtAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
return new RetrieveTaskSuccessResult((RetrieveTask) task, makeStatsRequest(),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);
return null;
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeActionRequest("urlUpload", url);
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
makeActionRequest((removeTask.includingData()? "deleteWithData": "delete"), 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("bulkStop", null);
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeActionRequest("start", task.getTargetTorrent().getUniqueID());
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
makeActionRequest("bulkStart", null);
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 (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
}
}
private List<Torrent> makeStatsRequest() throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl(RPC_URL_STATS));
HttpResponse response = httpclient.execute(httpget);
// Read XML response
InputStream instream = response.getEntity().getContent();
List<Torrent> torrents = StatsParser.parse(new InputStreamReader(instream));
instream.close();
return torrents;
} catch (DaemonException e) {
DLog.d(LOG_NAME, "Parsing error: " + e.toString());
throw e;
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private boolean makeActionRequest(String action, String target) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
// Make request
HttpGet httpget = new HttpGet(buildWebUIUrl(RPC_URL_DISPATCH + action + RPC_URL_DISPATCH2 + RPC_URL_AID + (action.equals("urlUpload")? RPC_URL_URL: RPC_URL_TRANSFER) + target));
HttpResponse response = httpclient.execute(httpget);
// Read response (a successful action always returned '1')
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
if (result.trim().equals("1")) {
return true;
} else {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Action response was not 1 but " + result);
}
} catch (DaemonException e) {
DLog.d(LOG_NAME, action + " request error: " + e.toString());
throw e;
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
private boolean makeFileUploadRequest(String action, String target) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
// Make request
HttpPost httppost = new HttpPost(buildWebUIUrl(RPC_URL_DISPATCH + action + RPC_URL_DISPATCH2 + RPC_URL_AID));
File upload = new File(URI.create(target));
Part[] parts = { new FilePart("upload_files[]", upload) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
HttpResponse response = httpclient.execute(httppost);
// Read response (a successful action always returned '1')
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
instream.close();
if (result.equals("1")) {
return true;
} else {
throw new DaemonException(ExceptionType.UnexpectedResponse, "Action response was not 1 but " + result);
}
} catch (DaemonException e) {
DLog.d(LOG_NAME, action + " request error: " + e.toString());
throw e;
} catch (Exception e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
}
}
/**
* 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 {
httpclient = HttpHelper.createStandardHttpClient(settings, true);
}
/**
* Build the URL of specific Torrentflux site request from the user settings and some requested action.
* @param act The action to perform, which is an already build query string without usernmae/password, i.e. dispatcher.php?action=stop&transfer=ubuntu.torrent
* @return The URL of a specific request, i.e. http://localhost:80/turrentflux/dispatcher.php?action=stop&transfer=ubuntu.torrent&username=admin&md5pass=asd98as7d
*/
private String buildWebUIUrl(String act) {
String folder = settings.getFolder().endsWith("/")?
settings.getFolder().substring(0, settings.getFolder().length() - 1):
settings.getFolder();
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() +
folder + act + RPC_URL_USER + settings.getUsername() + RPC_URL_PASS + md5Pass((settings.getPassword() == null? "": settings.getPassword()));
}
/**
* Calculate the MD5 hash of a password to use with the Torrentflux-b4rt dispatcher requests.
* @param pass The plain text password
* @return A hex-formatted MD5-hashed string of the password
*/
public static String md5Pass(String pass) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] data = pass.getBytes();
m.update(data,0,data.length);
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032X", i);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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.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.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
import org.transdroid.daemon.task.PauseTask;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.ResumeTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
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.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;
/**
* The daemon adapter from the Deluge torrent client.
*
* @author erickok
*
*/
public class DelugeAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "Deluge daemon";
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";
private static final String RPC_RESULT = "result";
private static final String RPC_TORRENTS = "torrents";
private static final String RPC_FILE = "file";
private static final String RPC_FILES = "files";
private static final String RPC_SESSION_ID = "_session_id";
private static final String RPC_METHOD_LOGIN = "auth.login";
private static final String RPC_METHOD_GET = "web.update_ui";
private static final String RPC_METHOD_STATUS = "core.get_torrent_status";
private static final String RPC_METHOD_ADD = "core.add_torrent_url";
private static final String RPC_METHOD_ADD_MAGNET = "core.add_torrent_magnet";
private static final String RPC_METHOD_ADD_FILE = "web.add_torrents";
private static final String RPC_METHOD_REMOVE = "core.remove_torrent";
private static final String RPC_METHOD_PAUSE = "core.pause_torrent";
private static final String RPC_METHOD_PAUSE_ALL = "core.pause_all_torrents";
private static final String RPC_METHOD_RESUME = "core.resume_torrent";
private static final String RPC_METHOD_RESUME_ALL = "core.resume_all_torrents";
private static final String RPC_METHOD_SETCONFIG = "core.set_config";
private static final String RPC_METHOD_SETFILE = "core.set_torrent_file_priorities";
//private static final String RPC_METHOD_SETOPTIONS = "core.set_torrent_options";
private static final String RPC_METHOD_MOVESTORAGE = "core.move_storage";
private static final String RPC_METHOD_SETTRACKERS = "core.set_torrent_trackers";
private static final String RPC_NAME = "name";
private static final String RPC_STATUS = "state";
private static final String RPC_MESSAGE = "message";
private static final String RPC_SAVEPATH = "save_path";
private static final String RPC_MAXDOWNLOAD = "max_download_speed";
private static final String RPC_MAXUPLOAD = "max_upload_speed";
private static final String RPC_RATEDOWNLOAD = "download_payload_rate";
private static final String RPC_RATEUPLOAD = "upload_payload_rate";
private static final String RPC_PEERSGETTING = "num_seeds";
private static final String RPC_PEERSSENDING = "num_seeds";
private static final String RPC_PEERSCONNECTED = "num_peers";
private static final String RPC_PEERSKNOWN = "total_peers";
private static final String RPC_ETA = "eta";
private static final String RPC_TIMEADDED = "time_added";
private static final String RPC_DOWNLOADEDEVER = "total_done";
private static final String RPC_UPLOADEDEVER = "total_uploaded";
private static final String RPC_TOTALSIZE = "total_size";
private static final String RPC_PARTDONE = "progress";
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 NO_LABEL = "No Label";
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_PEERSGETTING, RPC_PEERSSENDING, RPC_PEERSCONNECTED,
RPC_PEERSKNOWN, 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;
public DelugeAdapter(DaemonSettings settings) {
this.settings = settings;
}
public JSONArray AddTorrentByFile(String file) throws JSONException, ClientProtocolException, IOException, DaemonException {
String url = buildWebUIUrl() + PATH_TO_UPLOAD;
DLog.d(LOG_NAME, "Uploading a file to the Deluge daemon: " + url);
// Initialise the HTTP client
if (httpclient == null) {
initialise();
}
// Setup client using POST
HttpPost httppost = new HttpPost(url);
File upload = new File(URI.create(file));
Part[] parts = { new FilePart(RPC_FILE, upload) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
// Make request
HttpResponse response = httpclient.execute(httppost);
// Read JSON response
InputStream instream = response.getEntity().getContent();
String result = HttpHelper.ConvertStreamToString(instream);
// If the upload succeeded, add the torrent file on the server
// For this we need the file name, which is now send as a JSON object like:
// {"files": ["/tmp/delugeweb/tmp00000.torrent"], "success": true}
String remoteFile = (new JSONObject(result)).getJSONArray(RPC_FILES).getString(0);
JSONArray params = new JSONArray();
JSONArray files = new JSONArray();
JSONObject fileu = new JSONObject();
fileu.put("path", remoteFile);
fileu.put("options", new JSONArray());
files.put(fileu);
params.put(files);
return params;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
JSONArray params = new JSONArray();
// Array of the fields needed for files listing calls
JSONArray ffields = new JSONArray();
ffields.put(RPC_DETAILS);
ffields.put(RPC_FILEPROGRESS);
ffields.put(RPC_FILEPRIORITIES);
switch (task.getMethod()) {
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)),null);
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();
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<TorrentFile> 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));
}
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:
// TODO: This doesn't seem to work; totally undocumented and also broken in the web UI so won't fix for now
// Request to set the label
SetLabelTask labelTask = (SetLabelTask) task;
JSONObject labelMap = new JSONObject();
labelMap.put(RPC_LABEL, (labelTask.getNewLabel() == null? NO_LABEL: labelTask.getNewLabel()));
makeRequest(buildRequest(RPC_METHOD_SETCONFIG, (new JSONArray()).put(labelMap)));
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);
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()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (FileNotFoundException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
} catch (IOException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
}
}
/*private JSONArray buildSetTorrentOptions(String torrent, String key, String value) throws JSONException {
JSONArray params = new JSONArray();
params.put(new JSONArray().put(torrent)); // torrent_id
JSONObject sdlmap = new JSONObject();
// Set the option setting to the torrent
sdlmap.put(key, value);
params.put(sdlmap); // options
return params;
}*/
private JSONObject buildRequest(String sendMethod, JSONArray params) throws JSONException {
// Build request for method
JSONObject request = new JSONObject();
request.put(RPC_METHOD, sendMethod);
request.put(RPC_PARAMS, (params == null) ? new JSONArray() : params);
request.put(RPC_ID, 2);
return request;
}
private JSONObject makeRequest(JSONObject data) 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 || extraPass == "") {
extraPass = settings.getPassword();
}
JSONObject loginRequest = new JSONObject();
loginRequest.put(RPC_METHOD, RPC_METHOD_LOGIN);
loginRequest.put(RPC_PARAMS, (new JSONArray()).put(extraPass));
loginRequest.put(RPC_ID, 1);
// Set POST URL and data
HttpPost httppost = new HttpPost(buildWebUIUrl() + PATH_TO_RPC);
StringEntity se = new StringEntity(loginRequest.toString());
httppost.setEntity(se);
// Execute
HttpResponse response = httpclient.execute(httppost);
InputStream instream = response.getEntity().getContent();
// Retrieve session ID
if (!httpclient.getCookieStore().getCookies().isEmpty()) {
for (Cookie cookie : httpclient.getCookieStore().getCookies()) {
if (cookie.getName().equals(RPC_SESSION_ID)) {
sessionCookie = cookie;
break;
}
}
}
// 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));
}
}
// Regular action
// Set POST URL and data
HttpPost httppost = new HttpPost(buildWebUIUrl() + PATH_TO_RPC);
StringEntity se = new StringEntity(data.toString());
httppost.setEntity(se);
// Set session cookie, if it was not in the httpclient object yet
boolean cookiePresent = false;
for (Cookie cookie : httpclient.getCookieStore().getCookies()) {
if (cookie.getName().equals(RPC_SESSION_ID)) {
cookiePresent = true;
break;
}
}
if (!cookiePresent) {
httpclient.getCookieStore().addCookie(sessionCookie);
}
// Execute
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read JSON response
InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
JSONObject json = new JSONObject(result);
instream.close();
DLog.d(LOG_NAME, "Success: " + (result.length() > 300? result.substring(0, 300) + "... (" + result.length() + " chars)": result));
// Return JSON object
return json;
}
// No result?
throw new DaemonException(ExceptionType.UnexpectedResponse, "No HTTP entity in response object.");
} catch (JSONException e) {
DLog.d(LOG_NAME, "Error: " + e.toString());
throw new DaemonException(ExceptionType.UnexpectedResponse, e.toString());
} catch (Exception e) {
DLog.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);
}
/**
* 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());
}
private ArrayList<Torrent> parseJsonRetrieveTorrents(JSONObject response) throws JSONException, DaemonException {
// Parse response
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
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());
}
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);
//status = TorrentStatus.Error; // Don't report this as blocking error
}
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_PEERSGETTING),
tor.getInt(RPC_PEERSSENDING),
tor.getInt(RPC_PEERSCONNECTED),
tor.getInt(RPC_PEERSKNOWN),
tor.getInt(RPC_ETA),
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(tor.getInt(RPC_TIMEADDED) * 1000L): null,
null,
tor.getString(RPC_MESSAGE))); // Not available
}
}
// Return the list
return torrents;
}
private ArrayList<TorrentFile> parseJsonFileListing(JSONObject response, Torrent torrent) throws JSONException {
// Parse response
ArrayList<TorrentFile> files = new ArrayList<TorrentFile>();
JSONArray objects = response.getJSONArray(RPC_DETAILS);
JSONArray progress = response.getJSONArray(RPC_FILEPROGRESS);
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
files.add(new TorrentFile(
"" + file.getInt(RPC_INDEX),
file.getString(RPC_PATH),
file.getString(RPC_PATH),
torrent.getLocationDir() + file.getString(RPC_PATH),
file.getLong(RPC_SIZE),
(long) (progress.getDouble(j) * file.getLong(RPC_SIZE)),
convertDelugePriority(priorities.getInt(j))));
}
}
// Return the list
return files;
}
private Priority convertDelugePriority(int priority) {
switch (priority) {
case 0:
return Priority.Off;
case 2:
return Priority.Normal;
case 5:
return Priority.High;
default:
return Priority.Low;
}
}
private int convertPriority(Priority priority) {
switch (priority) {
case Off:
return 0;
case Normal:
return 2;
case High:
return 5;
default:
return 1;
}
}
private TorrentStatus convertDelugeState(String state) {
// Deluge sends a string with status code
if (state.compareTo("Paused") == 0) {
return TorrentStatus.Paused;
} else if (state.compareTo("Seeding") == 0) {
return TorrentStatus.Seeding;
} else if (state.compareTo("Downloading") == 0 || state.compareTo("Active") == 0) {
return TorrentStatus.Downloading;
} else if (state.compareTo("Checking") == 0) {
return TorrentStatus.Checking;
} else if (state.compareTo("Queued") == 0) {
return TorrentStatus.Queued;
}
return TorrentStatus.Unknown;
}
private TorrentDetails parseJsonTorrentDetails(JSONObject response) throws JSONException {
// Parse response
List<String> trackers = new ArrayList<String>();
JSONArray trackerObjects = response.getJSONArray(RPC_TRACKERS);
if (trackerObjects != null && trackerObjects.length() > 0) {
for (int i = 0; i < trackerObjects.length(); i++) {
trackers.add(trackerObjects.getJSONObject(i).getString("url"));
}
}
List<String> errors = new ArrayList<String>();
String trackerStatus = response.getString(RPC_TRACKER_STATUS);
errors.add(trackerStatus);
return new TorrentDetails(trackers, errors);
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.DLinkRouterBT;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
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.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.PauseTask;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.ResumeTask;
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;
import com.android.internalcopy.http.multipart.Part;
/**
* The daemon adapter for the DLink Router Bittorrent client.
*
* @author AvengerMoJo <avengermojo at gmail.com>
*
*/
public class DLinkRouterBTAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "DLinkRouterBT adapter";
private static final String PATH_TO_API = "/api/";
private static final String SESSION_HEADER = "X-Session-Id";
private static final String JSON_TORRENTS = "torrents";
private static final String API_GET = "torrents-get";
private static final String API_ADD = "torrent-add-url?start=yes&url=";
private static final String API_ADD_BY_FILE = "torrent-add?start=yes";
private static final String API_REMOVE = "torrent-remove?delete-torrent=yes&hash=";
private static final String API_DEL_DATA = "&delete-data=";
private static final String API_STOP = "torrent-stop?hash=";
private static final String API_START = "torrent-start?hash=";
private static final String BT_ADD_BY_FILE = "fileEl";
private static final String BT_CAPTION = "caption";
private static final String BT_COPYS = "distributed_copies";
private static final String BT_DOWNLOAD_RATE = "dl_rate";
private static final String BT_DONE = "done";
private static final String BT_HASH = "hash";
// private static final String BT_MAX_CONNECTED = "max_connections";
// private static final String BT_MAX_DOWNLOAD_RATE = "max_dl_rate";
// private static final String BT_MAX_UPLOAD_RATE = "max_ul_rate";
// private static final String BT_MAX_UPLOAD_CONNECTIONS = "max_uploads";
// private static final String BT_PAYLOAD_DOWNLOAD = "payload_download";
private static final String BT_PAYLOAD_UPLOAD = "payload_upload";
private static final String BT_PEERS_CONNECTED = "peers_connected";
private static final String BT_PEERS_TOTAL = "peers_total";
// private static final String BT_PRIVATE = "private";
// private static final String BT_SEEDS_CONNECTED = "seeds_connected";
// private static final String BT_SEEDS_TOTAL = "seeds_total";
private static final String BT_SIZE = "size";
private static final String BT_STATE = "state";
private static final String BT_STOPPED = "stopped";
private static final String BT_UPLOAD_RATE = "ul_rate";
private static final String API_GET_FILES = "torrent-get-files?hash=";
private static final String BT_FILE_DONE = "done";
private static final String BT_FILE_NAME = "name";
private static final String BT_FILE_SIZE = "size";
private static final String BT_FILE_PRIORITY = "pri";
private DaemonSettings settings;
private DefaultHttpClient httpclient;
private String sessionToken;
public DLinkRouterBTAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
// Request all torrents from server
JSONObject result = makeRequest(API_GET);
return new RetrieveTaskSuccessResult((RetrieveTask) task, parseJsonRetrieveTorrents(result),null);
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()));
case AddByFile:
// 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);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask) task).getUrl();
makeRequest(API_ADD + url);
return new DaemonTaskSuccessResult(task);
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);
// case Stop:
case Pause:
// Pause a torrent
PauseTask pauseTask = (PauseTask) task;
makeRequest(API_STOP + pauseTask.getTargetTorrent().getUniqueID(), false);
return new DaemonTaskSuccessResult(task);
// case PauseAll:
// Resume all torrents
// makeRequest(buildRequestObject(RPC_METHOD_PAUSE, buildTorrentRequestObject(FOR_ALL, null,
// false)));
// return new DaemonTaskSuccessResult(task);
// case Start:
case Resume:
// Resume a torrent
ResumeTask resumeTask = (ResumeTask) task;
makeRequest(API_START + resumeTask.getTargetTorrent().getUniqueID(), false);
return new DaemonTaskSuccessResult(task);
// case ResumeAll:
// Resume all torrents
// makeRequest(buildRequestObject(RPC_METHOD_RESUME, buildTorrentRequestObject(FOR_ALL, null,
// false)));
// return new DaemonTaskSuccessResult(task);
// case SetTransferRates:
// Request to set the maximum transfer rates
// SetTransferRatesTask ratesTask = (SetTransferRatesTask) task;
// if (ratesTask.getUploadRate() == null) {
// request.put(RPC_SESSION_LIMITUPE, false);
// } else {
// request.put(RPC_SESSION_LIMITUPE, true);
// request.put(RPC_SESSION_LIMITUP, ratesTask.getUploadRate().intValue());
// }
// if (ratesTask.getDownloadRate() == null) {
// request.put(RPC_SESSION_LIMITDOWNE, false);
// } else {
// request.put(RPC_SESSION_LIMITDOWNE, true);
// request.put(RPC_SESSION_LIMITDOWN, ratesTask.getDownloadRate().intValue());
// }
// makeRequest( RPC_METHOD_SESSIONSET );
// 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()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
}
}
private JSONObject makeRequest(String requestUrl, File upload) throws DaemonException {
return makeRequest(requestUrl, false, upload);
}
private JSONObject makeRequest(String requestUrl) throws DaemonException {
return makeRequest(requestUrl, true, null);
}
private JSONObject makeRequest(String requestUrl, boolean hasRespond) throws DaemonException {
return makeRequest(requestUrl, hasRespond, null);
}
private JSONObject makeRequest(String requestUrl, boolean hasRespond, File upload) throws DaemonException {
try {
// Initialise the HTTP client
if (httpclient == null) {
initialise(HttpHelper.DEFAULT_CONNECTION_TIMEOUT);
}
// 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) };
httppost.setEntity(new MultipartEntity(parts, httppost.getParams()));
}
// Send the stored session token as a header
if (sessionToken != null) {
httppost.addHeader(SESSION_HEADER, sessionToken);
}
// Execute
HttpResponse response = httpclient.execute(httppost);
// 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
sessionToken = response.getFirstHeader(SESSION_HEADER).getValue();
httppost.addHeader(SESSION_HEADER, sessionToken);
response = httpclient.execute(httppost);
}
if (!hasRespond)
return null;
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read JSON response
java.io.InputStream instream = entity.getContent();
String result = HttpHelper.ConvertStreamToString(instream);
JSONObject json = new JSONObject(result);
instream.close();
DLog.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");
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());
throw new DaemonException(ExceptionType.UnexpectedResponse, e.toString());
} catch (Exception e) {
DLog.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(int connectionTimeout) 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;
}
private TorrentStatus convertStatus(String state) {
if ("allocating".equals(state))
return TorrentStatus.Checking;
if ("seeding".equals(state))
return TorrentStatus.Seeding;
if ("finished".equals(state))
return TorrentStatus.Downloading;
if ("connecting_to_tracker".equals(state))
return TorrentStatus.Checking;
if ("queued_for_checking".equals(state))
return TorrentStatus.Queued;
if ("downloading".equals(state))
return TorrentStatus.Downloading;
return TorrentStatus.Unknown;
}
private ArrayList<Torrent> parseJsonRetrieveTorrents(JSONObject response) throws JSONException {
// Parse response
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
JSONArray rarray = response.getJSONArray(JSON_TORRENTS);
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)
status = TorrentStatus.Paused;
else
status = convertStatus(tor.getString(BT_STATE));
int eta = (int) (tor.getLong(BT_SIZE) / (tor.getInt(BT_DOWNLOAD_RATE) + 1));
if (0 > eta)
eta = -1;
Torrent new_t = new Torrent(
i,
tor.getString(BT_HASH),
tor.getString(BT_CAPTION),
status,
null, // Not supported?
tor.getInt(BT_DOWNLOAD_RATE),
tor.getInt(BT_UPLOAD_RATE),
tor.getInt(BT_PEERS_CONNECTED),
tor.getInt(BT_PEERS_CONNECTED),
tor.getInt(BT_PEERS_CONNECTED),
tor.getInt(BT_PEERS_TOTAL),
(int) ((tor.getLong(BT_SIZE) - tor.getLong(BT_DONE)) / (tor.getInt(BT_DOWNLOAD_RATE) + 1)),
tor.getLong(BT_DONE),
tor.getLong(BT_PAYLOAD_UPLOAD),
tor.getLong(BT_SIZE),
(float) (tor.getLong(BT_DONE) / (float) tor.getLong(BT_SIZE)),
Float.parseFloat(tor.getString(BT_COPYS)),
null,
null,
null,
null);
torrents.add(new_t);
}
// Return the list
return torrents;
}
private ArrayList<TorrentFile> parseJsonFileList(JSONObject response, String hash) throws JSONException {
// Parse response
ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
JSONObject jobj = response.getJSONObject(JSON_TORRENTS);
if (jobj != null) {
JSONArray files = jobj.getJSONArray(hash); // "Hash id"
for (int i = 0; i < files.length(); i++) {
JSONObject file = files.getJSONObject(i);
torrentfiles.add(new TorrentFile(
i + "",
// TODO: How is an individual file identified? Index in the array?
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))));
}
}
// Return the list
return torrentfiles;
}
private Priority convertTransmissionPriority(int priority) {
switch (priority) {
case 1:
return Priority.High;
case -1:
return Priority.Low;
default:
return Priority.Normal;
}
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Represents a torrent's fine details (currently only the trackers).
*
* @author erickok
*
*/
public final class TorrentDetails implements Parcelable {
private final List<String> trackers;
private final List<String> errors;
public TorrentDetails(List<String> trackers, List<String> errors) {
this.trackers = trackers;
this.errors = errors;
}
private TorrentDetails(Parcel in) {
this.trackers = in.createStringArrayList();
this.errors = in.createStringArrayList();
}
public List<String> getTrackers() {
return trackers;
}
public List<String> getErrors() {
return errors;
}
/**
* Builds a string with one tracker (URL) per line
* @return A \n-separated string of trackers
*/
public String getTrackersText() {
// Build a string with one tracker URL per line
String trackersText = "";
for (String tracker : trackers) {
trackersText += (trackersText.length() == 0? "": "\n") + tracker;
}
return trackersText;
}
/**
* Builds a string with one error per line
* @return A \n-separated string of errors
*/
public String getErrorsText() {
// Build a string with one tracker error per line
String errorsText = "";
for (String error : errors) {
errorsText += (errorsText.length() == 0? "": "\n") + error;
}
return errorsText;
}
public static final Parcelable.Creator<TorrentDetails> CREATOR = new Parcelable.Creator<TorrentDetails>() {
public TorrentDetails createFromParcel(Parcel in) {
return new TorrentDetails(in);
}
public TorrentDetails[] newArray(int size) {
return new TorrentDetails[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringList(trackers);
dest.writeStringList(errors);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Represents a label on a server daemon.
*
* @author Lexa
*
*/
public final class Label implements Parcelable, Comparable<Label> {
final private String name;
final private int count;
public String getName() { return name; }
public int getCount() { return count; }
private Label(Parcel in) {
this.name = in.readString();
this.count = in.readInt();
}
public Label(String name, int count) {
this.name = name;
this.count = count;
}
@Override
public String toString() {
return name;//+"("+String.valueOf(count)+")";
}
@Override
public int compareTo(Label another) {
// Compare Label objects on their name (used for sorting only!)
return name.compareTo(another.getName());
}
public static final Parcelable.Creator<Label> CREATOR = new Parcelable.Creator<Label>() {
public Label createFromParcel(Parcel in) {
return new Label(in);
}
public Label[] newArray(int size) {
return new Label[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(count);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.Vuze;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.openjpa.lib.util.Base16Encoder;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonMethod;
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.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
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
* is handled via the XML-RPC protocol.
*
* @author erickok
*
*/
public class VuzeAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "Vuze daemon";
private static final String RPC_URL = "/process.cgi";
private VuzeXmlOverHttpClient rpcclient;
private DaemonSettings settings;
private Long savedConnectionID;
private Long savedPluginID;
private Long savedDownloadManagerID;
private Long savedTorrentManagerID;
private Long savedPluginConfigID;
public VuzeAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
Object result = makeVuzeCall(DaemonMethod.Retrieve, "getDownloads");
return new RetrieveTaskSuccessResult((RetrieveTask) task, onTorrentsRetrieved(result),null);
case GetFileList:
// Retrieve a listing of the files in some torrent
Object fresult = makeVuzeCall(DaemonMethod.GetFileList, "getDiskManagerFileInfo", task.getTargetTorrent(), new Object[] {} );
return new GetFileListTaskSuccessResult((GetFileListTask) task, onTorrentFilesRetrieved(fresult, task.getTargetTorrent()));
case AddByFile:
byte[] bytes;
try {
// Request to add a torrent by local .torrent file
String file = ((AddByFileTask)task).getFile();
FileInputStream in = new FileInputStream(new File(URI.create(file)));
bytes = new byte[in.available()];
in.read(bytes, 0, in.available());
} catch (FileNotFoundException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
} catch (IllegalArgumentException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, "Invalid local URI"));
} catch (Exception e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
}
makeVuzeCall(DaemonMethod.AddByFile, "createFromBEncodedData[byte[]]", new String[] { Base16Encoder.encode(bytes) });
return new DaemonTaskSuccessResult(task);
case AddByUrl:
// Request to add a torrent by URL
String url = ((AddByUrlTask)task).getUrl();
makeVuzeCall(DaemonMethod.AddByUrl, "addDownload[URL]", new URL[] { new URL(url) });
return new DaemonTaskSuccessResult(task);
case Remove:
// Remove a torrent
RemoveTask removeTask = (RemoveTask) task;
if (removeTask.includingData()) {
makeVuzeCall(DaemonMethod.Remove, "remove[boolean,boolean]", task.getTargetTorrent(), new String[] { "true", "true"} );
} else {
makeVuzeCall(DaemonMethod.Remove, "remove", task.getTargetTorrent(), new Object[] {} );
}
return new DaemonTaskSuccessResult(task);
case Pause:
// Pause a torrent
makeVuzeCall(DaemonMethod.Pause, "stop", task.getTargetTorrent(), new Object[] {} );
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Resume all torrents
makeVuzeCall(DaemonMethod.ResumeAll, "stopAllDownloads");
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeVuzeCall(DaemonMethod.Start, "restart", task.getTargetTorrent(), new Object[] {} );
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
makeVuzeCall(DaemonMethod.ResumeAll, "startAllDownloads" );
return new DaemonTaskSuccessResult(task);
case SetFilePriorities:
// For each of the chosen files belonging to some torrent, set the priority
SetFilePriorityTask prioTask = (SetFilePriorityTask) task;
// One at a time; Vuze doesn't seem to support setting the isPriority or isSkipped on (a subset of) all files at once
for (TorrentFile forFile : prioTask.getForFiles()) {
if (prioTask.getNewPriority() == Priority.Off) {
makeVuzeCall(DaemonMethod.SetFilePriorities, "setSkipped[boolean]", Long.parseLong(forFile.getKey()), new String[] { "true" } );
} else if (prioTask.getNewPriority() == Priority.High) {
makeVuzeCall(DaemonMethod.SetFilePriorities, "setSkipped[boolean]", Long.parseLong(forFile.getKey()), new String[] { "false" } );
makeVuzeCall(DaemonMethod.SetFilePriorities, "setPriority[boolean]", Long.parseLong(forFile.getKey()), new String[] { "true" } );
} else {
makeVuzeCall(DaemonMethod.SetFilePriorities, "setSkipped[boolean]", Long.parseLong(forFile.getKey()), new String[] { "false" } );
makeVuzeCall(DaemonMethod.SetFilePriorities, "setPriority[boolean]", Long.parseLong(forFile.getKey()), new String[] { "false" } );
}
}
return new DaemonTaskSuccessResult(task);
case SetTransferRates:
// 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())} );
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (IOException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ConnectionError, e.toString()));
}
}
private Map<String, Object> makeVuzeCall(DaemonMethod method, String serverMethod, Torrent actOnTorrent, Object[] params) throws DaemonException {
return makeVuzeCall(method, serverMethod, Long.parseLong(actOnTorrent.getUniqueID()), params, actOnTorrent.getStatusCode());
}
private Map<String, Object> makeVuzeCall(DaemonMethod method, String serverMethod, Long actOnObject, Object[] params) throws DaemonException {
return makeVuzeCall(method, serverMethod, actOnObject, params, null);
}
private Map<String, Object> makeVuzeCall(DaemonMethod method, String serverMethod, Object[] params) throws DaemonException {
return makeVuzeCall(method, serverMethod, null, params, null);
}
private Map<String, Object> makeVuzeCall(DaemonMethod method, String serverMethod) throws DaemonException {
return makeVuzeCall(method, serverMethod, null, new Object[] {}, null);
}
private Map<String, Object> makeVuzeCall(DaemonMethod method, String serverMethod, Long actOnObject, Object[] params, TorrentStatus torrentStatus) throws DaemonException {
// TODO: It would be nicer to now split each of these steps into separate makeVuzeCalls when there are multiple logical steps such as stopping a torrent before removing it
// Initialise the HTTP client
if (rpcclient == null) {
initialise();
}
if (settings.getAddress() == null || settings.getAddress().equals("")) {
throw new DaemonException(DaemonException.ExceptionType.AuthenticationFailure, "No host name specified.");
}
if (savedConnectionID == null || savedPluginID == null) {
// Get plug-in interface (for connection and plug-in object IDs)
Map<String, Object> plugin = rpcclient.callXMLRPC(null, "getSingleton", null, null, false);
if (!plugin.containsKey("_connection_id")) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No connection ID returned on getSingleton request.");
}
savedConnectionID = (Long) plugin.get("_connection_id");
savedPluginID = (Long) plugin.get("_object_id");
}
// If no specific torrent was provided, get the download manager or plugin config to execute the method against
long vuzeObjectID;
if (actOnObject == null) {
if (method == DaemonMethod.SetTransferRates) {
// Execute this method against the plugin config (setParameter)
if (savedPluginConfigID == null) {
// Plugin config needed, but we don't know it's ID yet
Map<String, Object> config = rpcclient.callXMLRPC(savedPluginID, "getPluginconfig", null, savedConnectionID, false);
if (!config.containsKey("_object_id")) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No plugin config ID returned on getPluginconfig");
}
savedPluginConfigID = (Long) config.get("_object_id");
vuzeObjectID = savedPluginConfigID;
} else {
// We stored the plugin config ID, so no need to ask for it again
vuzeObjectID = savedPluginConfigID;
}
} else if (serverMethod.equals("createFromBEncodedData[byte[]]")) {
// Execute this method against the torrent manager (createFromBEncodedData)
if (savedTorrentManagerID == null) {
// Download manager needed, but we don't know it's ID yet
Map<String, Object> manager = rpcclient.callXMLRPC(savedPluginID, "getTorrentManager", null, savedConnectionID, false);
if (!manager.containsKey("_object_id")) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No torrent manager ID returned on getTorrentManager");
}
savedTorrentManagerID = (Long) manager.get("_object_id");
vuzeObjectID = savedTorrentManagerID;
} else {
// We stored the torrent manager ID, so no need to ask for it again
vuzeObjectID = savedTorrentManagerID;
}
// And we will need the download manager as well later on (for addDownload after createFromBEncodedData)
if (savedDownloadManagerID == null) {
// Download manager needed, but we don't know it's ID yet
Map<String, Object> manager = rpcclient.callXMLRPC(savedPluginID, "getDownloadManager", null, savedConnectionID, false);
if (!manager.containsKey("_object_id")) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No download manager ID returned on getDownloadManager");
}
savedDownloadManagerID = (Long) manager.get("_object_id");
}
} else {
// Execute this method against download manager (addDownload, startAllDownloads, etc.)
if (savedDownloadManagerID == null) {
// Download manager needed, but we don't know it's ID yet
Map<String, Object> manager = rpcclient.callXMLRPC(savedPluginID, "getDownloadManager", null, savedConnectionID, false);
if (!manager.containsKey("_object_id")) {
throw new DaemonException(ExceptionType.UnexpectedResponse, "No download manager ID returned on getDownloadManager");
}
savedDownloadManagerID = (Long) manager.get("_object_id");
vuzeObjectID = savedDownloadManagerID;
} else {
// We stored the download manager ID, so no need to ask for it again
vuzeObjectID = savedDownloadManagerID;
}
}
} else {
vuzeObjectID = actOnObject;
}
if (method == DaemonMethod.Remove && torrentStatus != null && torrentStatus != TorrentStatus.Paused) {
// Vuze, for some strange reason, wants us to stop the torrent first before removing it
rpcclient.callXMLRPC(vuzeObjectID, "stop", new Object[] {}, savedConnectionID, false);
}
boolean paramsAreVuzeObjects = false;
if (serverMethod.equals("createFromBEncodedData[byte[]]")) {
// Vuze does not directly add the torrent that we are uploading the file contents of
// We first do the createFromBEncodedData call and next actually add it
Map<String, Object> torrentData = rpcclient.callXMLRPC(vuzeObjectID, serverMethod, params, savedConnectionID, false);
serverMethod = "addDownload[Torrent]";
vuzeObjectID = savedDownloadManagerID;
params = new String[] { ((Long) torrentData.get("_object_id")).toString() };
paramsAreVuzeObjects = true;
}
// Call the actual method we wanted
return rpcclient.callXMLRPC(vuzeObjectID, serverMethod, params, savedConnectionID, paramsAreVuzeObjects);
}
/**
* Instantiates a Vuze XML over HTTP client with proper credentials.
* @throws DaemonException On conflicting settings (i.e. user authentication but no password or username provided)
*/
private void initialise() throws DaemonException {
this.rpcclient = new VuzeXmlOverHttpClient(settings, buildWebUIUrl());
}
/**
* Build the URL of the Vuze XML over HTTP plugin listener from the user settings.
* @return The URL of the RPC API
*/
private String buildWebUIUrl() {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + RPC_URL;
}
@SuppressWarnings("unchecked")
private List<Torrent> onTorrentsRetrieved(Object result) throws DaemonException {
Map<String, Object> response = (Map<String, Object>) result;
// We might have an empty list if no torrents are on the server
if (response == null) {
return new ArrayList<Torrent>();
}
DLog.d(LOG_NAME, response.toString().length() > 300? response.toString().substring(0, 300) + "... (" + response.toString().length() + " chars)": response.toString());
List<Torrent> torrents = new ArrayList<Torrent>();
// Parse torrent list from Vuze response, which is a map list of ENTRYs
for (String key : response.keySet()) {
/**
* Every Vuze ENTRY is a map of key-value pairs with information, or a key-map pair with that map being a mapping of key-value pairs with information
* VuzeXmlTorrentListResponse.txt in the Transdroid wiki shows a full example response, but it looks something like:
* ENTRY0={
position=1,
torrent_file=/home/erickok/.azureus/torrents/ubuntu.torrent,
name=ubuntu-9.04-desktop-i386.iso,
torrent={
size=732909568,
creation_date=1240473087
}
}
*/
Map<String, Object> info = (Map<String, Object>) response.get(key);
if (info == null || !info.containsKey("_object_id") || ((Long)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 <info> attached or no <_object_id> is available");
}
Map<String, Object> torrentinfo = (Map<String, Object>) info.get("torrent");
Map<String, Object> statsinfo = (Map<String, Object>) info.get("stats");
Map<String, Object> scrapeinfo = (Map<String, Object>) info.get("scrape_result");
Map<String, Object> announceinfo = (Map<String, Object>) info.get("announce_result");
int scrapeSeedCount = ((Long) scrapeinfo.get("seed_count")).intValue();
int scrapeNonSeedCount = ((Long) scrapeinfo.get("non_seed_count")).intValue();
String error = (String) info.get("error_state_details");
error = error != null && error.equals("")? null: error;
int announceSeedCount = ((Long) announceinfo.get("seed_count")).intValue();
int announceNonSeedCount = ((Long) announceinfo.get("non_seed_count")).intValue();
int rateDownload = ((Long) statsinfo.get("download_average")).intValue();
Double availability = (Double)statsinfo.get("availability");
Long size = torrentinfo != null? (Long)torrentinfo.get("size"): 0;
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
convertTorrentStatus((Long) info.get("state")), // status
(String) statsinfo.get("target_file_or_dir") + "/", // locationDir
rateDownload, // rateDownload
((Long)statsinfo.get("upload_average")).intValue(), // rateUpload
announceSeedCount, // peersGettingFromUs
announceNonSeedCount, // peersSendingToUs
scrapeSeedCount + scrapeNonSeedCount, // peersConnected
scrapeSeedCount + scrapeNonSeedCount, // peersKnown
(rateDownload > 0? (int)((Long)statsinfo.get("remaining") / rateDownload): -1), // eta (bytes left / rate download, if rate > 0)
(Long)statsinfo.get("downloaded"), // downloadedEver
(Long)statsinfo.get("uploaded"), // uploadedEver
size, // totalSize
(float)((Long)statsinfo.get("downloaded")) / (float)(size), // partDone (downloadedEver / totalSize)
Math.min(availability.floatValue(), 1f),
null, // TODO: Implement Vuze label support
new Date((Long) statsinfo.get("time_started")), // dateAdded
null, // Unsupported?
error));
}
return torrents;
}
@SuppressWarnings("unchecked")
private List<TorrentFile> onTorrentFilesRetrieved(Object result, Torrent torrent) {
Map<String, Object> response = (Map<String, Object>) result;
// We might have an empty list
if (response == null) {
return new ArrayList<TorrentFile>();
}
//DLog.d(LOG_NAME, response.toString().length() > 300? response.toString().substring(0, 300) + "... (" + response.toString().length() + " chars)": response.toString());
List<TorrentFile> files = new ArrayList<TorrentFile>();
// Parse torrent file list from Vuze response, which is a map list of ENTRYs
for (String key : response.keySet()) {
/**
* Every Vuze ENTRY is a map of key-value pairs with information
* For file lists, it looks something like:
* ENTRY2={
is_deleted=false,
length=298,
downloaded=298,
is_priority=false,
first_piece_number=726,
is_skipped=false,
file=/var/data/Downloads/Some.Torrent/OneFile.txt,
_object_id=443243294889782236,
num_pieces=1,
access_mode=1
}
*/
Map<String, Object> info = (Map<String, Object>) response.get(key);
String file = (String)info.get("file");
files.add(new TorrentFile(
"" + (Long)info.get("_object_id"),
new File(file).getName(), // name
(file.length() > torrent.getLocationDir().length()? file.substring(torrent.getLocationDir().length()): file), // name
file, // fullPath
(Long)info.get("length"), // size
(Long)info.get("downloaded"), // downloaded
convertVuzePriority((String)info.get("is_skipped"), (String)info.get("is_priority")))); // priority
}
return files;
}
private Priority convertVuzePriority(String isSkipped, String isPriority) {
return isSkipped.equals("true")? Priority.Off: (isPriority.equals("true")? Priority.High: Priority.Normal);
}
private TorrentStatus convertTorrentStatus(Long state) {
switch (state.intValue()) {
case 2:
return TorrentStatus.Checking;
case 4:
return TorrentStatus.Downloading;
case 5:
return TorrentStatus.Seeding;
case 7:
return TorrentStatus.Paused;
case 8:
return TorrentStatus.Error;
}
return TorrentStatus.Unknown;
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.Vuze;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.base64.android.Base64;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.util.FakeSocketFactory;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import android.util.Xml;
/**
* Implements an XML-RPC-like client that build and parses XML following
* Vuze's XML over HTTP plug-in (which unfortunately is incompatible with
* the default XML-RPC protocol).
*
* The documentation can be found at http://azureus.sourceforge.net/plugin_details.php?plugin=xml_http_if&docu=1#1
* and some stuff is at http://wiki.vuze.com/index.php/XML_over_HTTP
*
* A lot of it is copied from the org.xmlrpc.android library's XMLRPCClient
* as can be found at http://code.google.com/p/android-xmlrpc
*
* @author erickok
*
*/
public class VuzeXmlOverHttpClient {
private final static String TAG_REQUEST = "REQUEST";
private final static String TAG_OBJECT = "OBJECT";
private final static String TAG_OBJECT_ID = "_object_id";
private final static String TAG_METHOD = "METHOD";
private final static String TAG_PARAMS = "PARAMS";
private final static String TAG_ENTRY = "ENTRY";
private final static String TAG_INDEX = "index";
private final static String TAG_CONNECTION_ID = "CONNECTION_ID";
private final static String TAG_REQUEST_ID = "REQUEST_ID";
private final static String TAG_RESPONSE = "RESPONSE";
private final static String TAG_ERROR = "ERROR";
private final static String TAG_TORRENT = "torrent";
private final static String TAG_STATS = "stats";
private final static String TAG_ANNOUNCE = "announce_result";
private final static String TAG_SCRAPE = "scrape_result";
private final static String TAG_CACHED_PROPERTY_NAMES = "cached_property_names";
private DefaultHttpClient client;
private HttpPost postMethod;
private Random random;
private String username;
private String password;
/**
* XMLRPCClient constructor. Creates new instance based on server URI
* @param settings The server connection settings
* @param uri The URI of the XML RPC to connect to
* @throws DaemonException Thrown when settings are missing or conflicting
*/
public VuzeXmlOverHttpClient(DaemonSettings settings, URI uri) throws DaemonException {
postMethod = new HttpPost(uri);
postMethod.addHeader("Content-Type", "text/xml");
// WARNING
// I had to disable "Expect: 100-Continue" header since I had
// two second delay between sending http POST request and POST body
HttpParams httpParams = postMethod.getParams();
HttpProtocolParams.setUseExpectContinue(httpParams, false);
HttpConnectionParams.setConnectionTimeout(httpParams, settings.getTimeoutInMilliseconds());
HttpConnectionParams.setSoTimeout(httpParams, settings.getTimeoutInMilliseconds());
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", new PlainSocketFactory(), 80));
SocketFactory https_socket =
settings.getSslTrustAll() ? new FakeSocketFactory()
: settings.getSslTrustKey() != null ? new FakeSocketFactory(settings.getSslTrustKey())
: SSLSocketFactory.getSocketFactory();
registry.register(new Scheme("https", https_socket, 443));
client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams);
if (settings.shouldUseAuthentication()) {
if (settings.getUsername() == null || settings.getPassword() == null) {
throw new DaemonException(DaemonException.ExceptionType.AuthenticationFailure, "No username or password set, while authentication was enabled.");
} else {
username = settings.getUsername();
password = settings.getPassword();
((DefaultHttpClient) client).getCredentialsProvider().setCredentials(
new AuthScope(postMethod.getURI().getHost(), postMethod.getURI().getPort(), AuthScope.ANY_REALM),
new UsernamePasswordCredentials(username, password));
}
}
random = new Random();
random.nextInt();
}
/**
* Convenience constructor. Creates new instance based on server String address
* @param settings The server connection settings
* @param uri The URI of the XML RPC to connect to
* @throws DaemonException Thrown when settings are missing or conflicting
*/
public VuzeXmlOverHttpClient(DaemonSettings settings, String url) throws DaemonException {
this(settings, URI.create(url));
}
protected Map<String, Object> callXMLRPC(Long object, String method, Object[] params, Long connectionID, boolean paramsAreVuzeObjects) throws DaemonException {
try {
// prepare POST body
XmlSerializer serializer = Xml.newSerializer();
StringWriter bodyWriter = new StringWriter();
serializer.setOutput(bodyWriter);
serializer.startDocument(null, null);
serializer.startTag(null, TAG_REQUEST);
// set object
if (object != null) {
serializer.startTag(null, TAG_OBJECT).startTag(null, TAG_OBJECT_ID)
.text(object.toString()).endTag(null, TAG_OBJECT_ID).endTag(null, TAG_OBJECT);
}
// set method
serializer.startTag(null, TAG_METHOD).text(method).endTag(null, TAG_METHOD);
if (params != null && params.length != 0) {
// set method params
serializer.startTag(null, TAG_PARAMS);
Integer entryIndex = 0;
for (Object param : params) {
serializer.startTag(null, TAG_ENTRY).attribute(null, TAG_INDEX, entryIndex.toString());
if (paramsAreVuzeObjects) {
serializer.startTag(null, TAG_OBJECT).startTag(null, TAG_OBJECT_ID);
}
serializer.text(serialize(param));
if (paramsAreVuzeObjects) {
serializer.endTag(null, TAG_OBJECT_ID).endTag(null, TAG_OBJECT);
}
serializer.endTag(null, TAG_ENTRY);
entryIndex++;
}
serializer.endTag(null, TAG_PARAMS);
}
// set connection id
if (connectionID != null) {
serializer.startTag(null, TAG_CONNECTION_ID).text(connectionID.toString()).endTag(null, TAG_CONNECTION_ID);
}
// set request id, which for this purpose is always a random number
Integer randomRequestID = new Integer(random.nextInt());
serializer.startTag(null, TAG_REQUEST_ID).text(randomRequestID.toString()).endTag(null, TAG_REQUEST_ID);
serializer.endTag(null, TAG_REQUEST);
serializer.endDocument();
// set POST body
HttpEntity entity = new StringEntity(bodyWriter.toString());
postMethod.setEntity(entity);
// Force preemptive authentication
// This makes sure there is an 'Authentication: ' header being send before trying and failing and retrying
// by the basic authentication mechanism of DefaultHttpClient
postMethod.addHeader("Authorization", "Basic " + Base64.encodeBytes((username + ":" + password).getBytes()));
// execute HTTP POST request
HttpResponse response = client.execute(postMethod);
// check status code
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
throw new DaemonException(ExceptionType.AuthenticationFailure, "HTTP " + HttpStatus.SC_UNAUTHORIZED + " response (so no user or password or incorrect ones)");
} else if (statusCode != HttpStatus.SC_OK) {
throw new DaemonException(ExceptionType.ConnectionError, "HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK);
}
// parse response stuff
//
// setup pull parser
XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
entity = response.getEntity();
//String temp = HttpHelper.ConvertStreamToString(entity.getContent());
//Reader reader = new StringReader(temp);
Reader reader = new InputStreamReader(entity.getContent());
pullParser.setInput(reader);
// lets start pulling...
pullParser.nextTag();
pullParser.require(XmlPullParser.START_TAG, null, TAG_RESPONSE);
// build list of returned values
int next = pullParser.nextTag(); // skip to first start tag in list
String name = pullParser.getName(); // get name of the first start tag
// Empty response?
if (next == XmlPullParser.END_TAG && name.equals(TAG_RESPONSE)) {
return null;
} else if (name.equals(TAG_ERROR)) {
// Error
String errorText = pullParser.nextText(); // the value of the ERROR
entity.consumeContent();
throw new DaemonException(ExceptionType.ConnectionError, errorText);
} else {
// Consume a list of ENTRYs?
if (name.equals(TAG_ENTRY)) {
Map<String, Object> entries = new HashMap<String, Object>();
for (int i = 0; name.equals(TAG_ENTRY); i++) {
entries.put(TAG_ENTRY + i, consumeEntry(pullParser));
name = pullParser.getName();
}
entity.consumeContent();
return entries;
} else {
// Only a single object was returned, not an entry listing
return consumeObject(pullParser);
}
}
} catch (IOException e) {
throw new DaemonException(ExceptionType.ConnectionError, e.toString());
} catch (XmlPullParserException e) {
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
}
}
private Map<String, Object> consumeEntry(XmlPullParser pullParser) throws XmlPullParserException, IOException {
int next = pullParser.nextTag();
String name = pullParser.getName();
// Consume the ENTRY objects
Map<String, Object> returnValues = new HashMap<String, Object>();
while (next == XmlPullParser.START_TAG) {
if (name.equals(TAG_TORRENT) || name.equals(TAG_ANNOUNCE) || name.equals(TAG_SCRAPE) || name.equals(TAG_STATS)) {
// One of the objects contained inside an entry
pullParser.nextTag();
returnValues.put(name, consumeObject(pullParser));
} else {
// An object text inside this entry (such as _connectionid)
returnValues.put(name, deserialize(pullParser.nextText()));
}
next = pullParser.nextTag(); // skip to next start tag
name = pullParser.getName(); // get name of the new start tag
}
// Consume ENTRY ending
pullParser.nextTag();
return returnValues;
}
private Map<String, Object> consumeObject(XmlPullParser pullParser) throws XmlPullParserException, IOException {
int next = XmlPullParser.START_TAG;
String name = pullParser.getName();
// Consume bottom-level (contains no objects of its own) object
Map<String, Object> returnValues = new HashMap<String, Object>();
while (next == XmlPullParser.START_TAG && !(name.equals(TAG_CACHED_PROPERTY_NAMES))) {
if (name.equals(TAG_TORRENT) || name.equals(TAG_ANNOUNCE) || name.equals(TAG_SCRAPE) || name.equals(TAG_STATS)) {
// One of the objects contained inside an object
pullParser.nextTag();
returnValues.put(name, consumeObject(pullParser));
} else {
// An object text inside this entry (such as _connectionid)
returnValues.put(name, deserialize(pullParser.nextText()));
}
next = pullParser.nextTag(); // skip to next start tag
name = pullParser.getName(); // get name of the new start tag
}
return returnValues;
}
private String serialize(Object value) {
return value.toString();
}
static Object deserialize(String rawText) {
// Null?
if (rawText == null || rawText.equals("null")) {
return null;
}
/* For now cast all integers as Long; this prevents casting problems later on when
* we know it's a long but the value was small so it is casted to an Integer here
// Integer?
try {
Integer integernum = Integer.parseInt(rawText);
return integernum;
} catch (NumberFormatException e) {
// Just continue trying the next type
}*/
// Long?
try {
Long longnum = Long.parseLong(rawText);
return longnum;
} catch (NumberFormatException e) {
// Just continue trying the next type
}
// Double?
try {
Double doublenum = Double.parseDouble(rawText);
return doublenum;
} catch (NumberFormatException e) {
// Just continue trying the next type
}
// String otherwise
return rawText;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum TorrentsSortBy {
Alphanumeric (1),
Status (2),
DateDone (3),
DateAdded (4),
UploadSpeed (5),
Ratio (6);
private int code;
private static final Map<Integer,TorrentsSortBy> lookup = new HashMap<Integer,TorrentsSortBy>();
static {
for(TorrentsSortBy s : EnumSet.allOf(TorrentsSortBy.class))
lookup.put(s.getCode(), s);
}
TorrentsSortBy(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static TorrentsSortBy getStatus(int code) {
return lookup.get(code);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum TorrentFilesSortBy {
Alphanumeric (1),
PartDone(2),
TotalSize(3);
private int code;
private static final Map<Integer,TorrentFilesSortBy> lookup = new HashMap<Integer,TorrentFilesSortBy>();
static {
for(TorrentFilesSortBy s : EnumSet.allOf(TorrentFilesSortBy.class))
lookup.put(s.getCode(), s);
}
TorrentFilesSortBy(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static TorrentFilesSortBy getStatus(int code) {
return lookup.get(code);
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.base64.android.Base64;
import org.base64.android.Base64.InputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetStatsTask;
import org.transdroid.daemon.task.GetStatsTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
import org.transdroid.daemon.task.PauseTask;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.ResumeTask;
import org.transdroid.daemon.task.RetrieveTask;
import org.transdroid.daemon.task.RetrieveTaskSuccessResult;
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;
/**
* 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";
private static final String RPC_ERROR = "error";
private static final String RPC_ERRORSTRING = "errorString";
private static final String RPC_DOWNLOADDIR = "downloadDir";
private static final String RPC_RATEDOWNLOAD = "rateDownload";
private static final String RPC_RATEUPLOAD = "rateUpload";
private static final String RPC_PEERSGETTING = "peersGettingFromUs";
private static final String RPC_PEERSSENDING = "peersSendingToUs";
private static final String RPC_PEERSCONNECTED = "peersConnected";
//private static final String RPC_PEERSKNOWN = "peersKnown";
private static final String RPC_ETA = "eta";
private static final String RPC_DOWNLOADSIZE1 = "haveUnchecked";
private static final String RPC_DOWNLOADSIZE2 = "haveValid";
private static final String RPC_UPLOADEDEVER = "uploadedEver";
private static final String RPC_TOTALSIZE = "sizeWhenDone";
private static final String RPC_DATEADDED = "addedDate";
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 DaemonSettings settings;
private DefaultHttpClient httpclient;
private String sessionToken;
private long rpcVersion = -1;
public TransmissionAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
// Get the server version
if (rpcVersion <= -1) {
// Get server session statistics
JSONObject response = makeRequest(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());
}
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()));
}
} catch (JSONException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ParsingFailed, e.toString()));
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (FileNotFoundException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
} catch (IOException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
}
}
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 {
// Build request for one specific torrent
JSONObject request = new JSONObject();
if (torrentID != FOR_ALL) {
JSONArray ids = new JSONArray();
ids.put(torrentID); // The only id to add
request.put("ids", ids);
}
if (extraKey != null) {
request.put(extraKey, extraValue);
}
return request;
}
private JSONObject buildRequestObject(String sendMethod, JSONObject arguments) throws JSONException {
// Build request for method
JSONObject request = new JSONObject();
request.put("method", sendMethod);
request.put("arguments", arguments);
request.put("tag", 0);
return request;
}
private JSONObject makeRequest(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
HttpResponse response = httpclient.execute(httppost);
// Authentication error?
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
sessionToken = response.getFirstHeader(sessionHeader).getValue();
httppost.addHeader(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);
JSONObject json = new JSONObject(result);
instream.close();
//TLog.d(LOG_NAME, "Success: " + (result.length() > 200? result.substring(0, 200) + "... (" + result.length() + " chars)": result));
// Return the JSON object
return json;
}
DLog.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());
throw new DaemonException(ExceptionType.ParsingFailed, e.toString());
} catch (Exception e) {
DLog.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
*/
private String buildWebUIUrl() {
return (settings.getSsl() ? "https://" : "http://") + settings.getAddress() + ":" + settings.getPort() + (settings.getFolder() == null? "": settings.getFolder()) + "/transmission/rpc";
}
private ArrayList<Torrent> parseJsonRetrieveTorrents(JSONObject response) throws JSONException {
// Parse response
ArrayList<Torrent> torrents = new ArrayList<Torrent>();
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));
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
boolean hasError = tor.getInt(RPC_ERROR) == 3;
String errorString = tor.getString(RPC_ERRORSTRING).trim();
String commentString = tor.getString(RPC_COMMENT).trim();
if (!commentString.equals("")) {
errorString = errorString.equals("")? commentString : errorString + "\n" + commentString;
}
torrents.add(new Torrent(
tor.getInt(RPC_ID),
null,
tor.getString(RPC_NAME),
hasError? TorrentStatus.Error: getStatus(tor.getInt(RPC_STATUS)),
tor.getString(RPC_DOWNLOADDIR) + settings.getOS().getPathSeperator(),
tor.getInt(RPC_RATEDOWNLOAD),
tor.getInt(RPC_RATEUPLOAD),
tor.getInt(RPC_PEERSGETTING),
tor.getInt(RPC_PEERSSENDING),
tor.getInt(RPC_PEERSCONNECTED),
tor.getInt(RPC_PEERSCONNECTED),
tor.getInt(RPC_ETA),
tor.getLong(RPC_DOWNLOADSIZE1) + tor.getLong(RPC_DOWNLOADSIZE2),
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
new Date(tor.getLong(RPC_DATEADDED) * 1000L),
new Date(tor.getLong(RPC_DATEDONE) * 1000L),
errorString));
}
// Return the list
return torrents;
}
private TorrentStatus getStatus(int status) {
if (rpcVersion <= -1) {
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;
}
return TorrentStatus.Unknown;
} else {
return TorrentStatus.getStatus(status);
}
}
private ArrayList<TorrentFile> parseJsonFileList(JSONObject response, Torrent torrent) throws JSONException {
// Parse response
ArrayList<TorrentFile> torrentfiles = new ArrayList<TorrentFile>();
JSONArray rarray = response.getJSONArray("torrents");
if (rarray.length() > 0) {
JSONArray files = rarray.getJSONObject(0).getJSONArray("files");
JSONArray fileStats = rarray.getJSONObject(0).getJSONArray("fileStats");
for (int i = 0; i < files.length(); i++) {
JSONObject file = files.getJSONObject(i);
JSONObject stat = fileStats.getJSONObject(i);
torrentfiles.add(new TorrentFile(
"" + 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))));
}
}
// Return the list
return torrentfiles;
}
private Priority convertTransmissionPriority(boolean isWanted, int priority) {
if (!isWanted) {
return Priority.Off;
} else {
switch (priority) {
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");
if (rarray.length() > 0) {
JSONArray trackersList = rarray.getJSONObject(0).getJSONArray("trackers");
List<String> trackers = new ArrayList<String>();
for (int i = 0; i < trackersList.length(); i++) {
trackers.add(trackersList.getJSONObject(i).getString("announce"));
}
JSONArray trackerStatsList = rarray.getJSONObject(0).getJSONArray("trackerStats");
List<String> errors = new ArrayList<String>();
for (int i = 0; i < trackerStatsList.length(); i++) {
// Get the tracker response and if it was an error then add it
String lar = trackerStatsList.getJSONObject(i).getString("lastAnnounceResult");
if (lar != null && !lar.equals("") && !lar.equals("Success")) {
errors.add(lar);
}
}
return new TorrentDetails(trackers, errors);
}
return null;
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a file or torrent priority.
*
* @author erickok
*
*/
public enum Priority {
Off (0),
Low (1),
Normal (2),
High (3);
private int code;
private static final Map<Integer,Priority> lookup = new HashMap<Integer,Priority>();
static {
for(Priority s : EnumSet.allOf(Priority.class))
lookup.put(s.getCode(), s);
}
Priority(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static Priority getPriority(int code) {
return lookup.get(code);
}
public int comparePriorityTo(Priority another) {
return new Integer(this.getCode()).compareTo(new Integer(another.getCode()));
}
}
| Java |
package org.transdroid.daemon.util;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class FakeSocketFactory implements SocketFactory, LayeredSocketFactory {
private String certKey = null;
private SSLContext sslcontext = null;
public FakeSocketFactory(String certKey){
this.certKey = certKey;
}
public FakeSocketFactory() { }
private static SSLContext createEasySSLContext(String certKey) throws IOException {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { new FakeTrustManager(certKey) }, null);
return context;
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
private SSLContext getSSLContext() throws IOException {
if (this.sslcontext == null) {
this.sslcontext = createEasySSLContext(this.certKey);
}
return this.sslcontext;
}
@Override
public Socket connectSocket(Socket sock, String host, int port,
InetAddress localAddress, int localPort, HttpParams params) throws IOException,
UnknownHostException, ConnectTimeoutException {
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
if ((localAddress != null) || (localPort > 0)) {
// we need to bind explicitly
if (localPort < 0) {
localPort = 0; // indicates "any"
}
InetSocketAddress isa = new InetSocketAddress(localAddress,
localPort);
sslsock.bind(isa);
}
sslsock.connect(remoteAddress, connTimeout);
sslsock.setSoTimeout(soTimeout);
return sslsock;
}
@Override
public Socket createSocket() throws IOException {
return getSSLContext().getSocketFactory().createSocket();
}
@Override
public boolean isSecure(Socket arg0) throws IllegalArgumentException {
return true;
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
}
}
| Java |
package org.transdroid.daemon.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class FakeTrustManager implements X509TrustManager {
private String certKey = null;
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
private static final String LOG_NAME = "TrustManager";
FakeTrustManager(String certKey){
super();
this.certKey = certKey;
}
FakeTrustManager(){
super();
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if( this.certKey == null ){
// This is the Accept All certificates case.
return;
}
// Otherwise, we have a certKey defined. We should now examine the one we got from the server.
// They match? All is good. They don't, throw an exception.
String our_key = this.certKey.replaceAll("[^a-fA-F0-9]+", "");
try {
//Assume self-signed root is okay?
X509Certificate ss_cert = chain[0];
String thumbprint = FakeTrustManager.getThumbPrint(ss_cert);
DLog.d(LOG_NAME, thumbprint);
if( our_key.equalsIgnoreCase(thumbprint) ){
return;
}
else {
throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
}
} catch (NoSuchAlgorithmException e) {
throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
}
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
// Thank you: http://stackoverflow.com/questions/1270703/how-to-retrieve-compute-an-x509-certificates-thumbprint-in-java
private static String getThumbPrint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
return hexify(digest);
}
private static String hexify (byte bytes[]) {
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]);
}
return buf.toString();
}
}
| Java |
/*
* 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<F, S> {
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<F, S> other;
try {
other = (Pair<F, S>) 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 <A, B> Pair <A, B> create(A a, B b) {
return new Pair<A, B>(a, b);
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.util;
/**
* Universal logger; applications using this library should
* attach an ITLogger using <code>setLogger(ITLogger)</code>
* 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);
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.DaemonSettings;
/**
* Provides a set of general helper methods that can be used in web-based communication.
*
* @author erickok
*
*/
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 = null;
/**
* Creates a standard Apache HttpClient that is thread safe, supports different
* SSL auth methods and basic authentication
* @param settings The server settings to adhere
* @return An HttpClient that should be stored locally and reused for every new request
* @throws DaemonException Thrown when information (such as username/password) is missing
*/
public static DefaultHttpClient createStandardHttpClient(DaemonSettings settings, boolean userBasicAuth) throws DaemonException {
return createStandardHttpClient(userBasicAuth && settings.shouldUseAuthentication(), settings.getUsername(), settings.getPassword(), settings.getSslTrustAll(), settings.getSslTrustKey(), settings.getTimeoutInMilliseconds(), settings.getAddress(), settings.getPort());
}
/**
* Creates a standard Apache HttpClient that is thread safe, supports different
* SSL auth methods and basic authentication
* @param sslTrustAll Whether to trust all SSL certificates
* @param sslTrustkey A specific SSL key to accept exclusively
* @param timeout The connection timeout for all requests
* @param authAddress The authentication domain address
* @param authPort The authentication domain port number
* @return An HttpClient that should be stored locally and reused for every new request
* @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 {
// Register http and https sockets
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", new PlainSocketFactory(), 80));
SocketFactory https_socket = sslTrustAll ? new FakeSocketFactory()
: sslTrustkey != null ? new FakeSocketFactory(sslTrustkey) : SSLSocketFactory.getSocketFactory();
registry.register(new Scheme("https", https_socket, 443));
// Standard parameters
HttpParams httpparams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpparams, timeout);
HttpConnectionParams.setSoTimeout(httpparams, timeout);
if (userAgent != null) {
HttpProtocolParams.setUserAgent(httpparams, userAgent);
}
DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry), httpparams);
// Authentication credentials
if (userBasicAuth) {
if (username == null || password == null) {
throw new DaemonException(ExceptionType.AuthenticationFailure, "No username or password was provided while we hadauthentication enabled");
}
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 {
InputStreamReader isr;
if (encoding != null) {
isr = new InputStreamReader(is, encoding);
} else {
isr = new InputStreamReader(is);
}
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static String ConvertStreamToString(InputStream is) {
try {
return ConvertStreamToString(is, null);
} catch (UnsupportedEncodingException e) {
// Since this is going to use the default encoding, it is never going to crash on an UnsupportedEncodingException
e.printStackTrace();
return null;
}
}
} | Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.util;
/**
* Quick and dirty file size formatter.
*
* @author erickok
*
*/
public class FileSizeConverter {
private static final String DECIMAL_FORMATTER = "%.1f";
/**
* A quantity in which to express a file size.
*
* @author erickok
*
*/
public enum SizeUnit {
B,
KB,
MB,
GB
}
private static int INC_SIZE = 1024;
// Returns a file size given in bytes to a different unit, as a formatted string
public static String getSize(long from, SizeUnit to)
{
String out;
switch (to) {
case B:
out = String.valueOf(from);
break;
case KB:
out = String.format(DECIMAL_FORMATTER, ((double)from) / 1024);
break;
case MB:
out = String.format(DECIMAL_FORMATTER, ((double)from) / 1024 / 1024);
break;
default:
out = String.format(DECIMAL_FORMATTER, ((double)from) / 1024 / 1024 / 1024);
break;
}
return (out + " " + to.toString());
}
// Returns a file size in bytes in a nice readable formatted string
public static String getSize(long from) {
return getSize(from, true);
}
// Returns a file size in bytes in a nice readable formatted string
public static String getSize(long from, boolean withUnit) {
if (from < INC_SIZE) {
return String.valueOf(from) + (withUnit? SizeUnit.B.toString(): "");
} else if (from < (INC_SIZE * INC_SIZE)) {
return String.format(DECIMAL_FORMATTER, ((double)from) / INC_SIZE) + (withUnit? SizeUnit.KB.toString(): "");
} else if (from < (INC_SIZE * INC_SIZE * INC_SIZE)) {
return String.format(DECIMAL_FORMATTER, ((double)from) / INC_SIZE / INC_SIZE) + (withUnit? SizeUnit.MB.toString(): "");
} else {
return String.format(DECIMAL_FORMATTER, ((double)from) / INC_SIZE / INC_SIZE / INC_SIZE) + (withUnit? SizeUnit.GB.toString(): "");
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon.util;
/**
* Quick and dirty time calculations helper.
*
* @author erickok
*
*/
public class TimespanConverter {
private final static int ONE_MINUTE = 60;
private final static int ONE_HOUR = 60 * 60;
private final static int ONE_DAY = 60 * 60 * 24;
/**
* Returns a nicely formatted string of days, hours, minutes and seconds
* @param from The number of input seconds to convert
* @return A formatted string with separate days, hours, minutes and seconds
*/
public static String getTime(int from, boolean inDays) {
// less then ONE_MINUTE left
if (from < ONE_MINUTE) {
return String.valueOf(from) + "s";
// less than ONE_HOUR left
} else if (from < ONE_HOUR) {
return (from / ONE_MINUTE) + "m " + (from % ONE_MINUTE) + "s";
// less than ONE_DAY left
} else if (from < ONE_DAY) {
int whole_hours = (from / ONE_HOUR);
int whole_minutes = (from - (whole_hours * ONE_HOUR)) / ONE_MINUTE;
int seconds = (from - (whole_hours * ONE_HOUR) - (whole_minutes * ONE_MINUTE));
return whole_hours + "h " + whole_minutes + "m " + seconds + "s";
// over ONE_DAY left
} else {
int whole_days = (from / ONE_DAY);
int whole_hours = (from - (whole_days * ONE_DAY)) / ONE_HOUR;
int whole_dayshours = (from / ONE_HOUR);
int whole_minutes = (from - (whole_days * ONE_DAY) - (whole_hours * ONE_HOUR)) / ONE_MINUTE;
int seconds = (from - (whole_days * ONE_DAY) - (whole_hours * ONE_HOUR) - (whole_minutes * ONE_MINUTE));
if (inDays) {
return whole_days + "d " + whole_hours + "h " + whole_minutes + "m " + seconds + "s";
} else {
return whole_dayshours + "h " + whole_minutes + "m " + seconds + "s";
}
}
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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
* <code>TLog.setLogger(ITLogger)</code>
*
* @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);
}
| Java |
package org.transdroid.daemon.util;
import java.util.Iterator;
/**
* Helpers on Collections
*/
public class Collections2 {
/**
* Create a String from an iterable with a separator. Exemple: mkString({1,2,3,4}, ":" => "1:2:3:4"
*/
public static <T> String joinString(Iterable<T> iterable, String separator) {
boolean first = true;
String result = "";
Iterator<T> it = iterable.iterator();
while (it.hasNext()) {
result = (first ? "" : separator) + it.next().toString();
first = false;
}
return result;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
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.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.base64.android.Base64;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.DaemonException;
import org.transdroid.daemon.DaemonSettings;
import org.transdroid.daemon.IDaemonAdapter;
import org.transdroid.daemon.Priority;
import org.transdroid.daemon.Torrent;
import org.transdroid.daemon.TorrentDetails;
import org.transdroid.daemon.TorrentFile;
import org.transdroid.daemon.TorrentStatus;
import org.transdroid.daemon.DaemonException.ExceptionType;
import org.transdroid.daemon.task.AddByFileTask;
import org.transdroid.daemon.task.AddByMagnetUrlTask;
import org.transdroid.daemon.task.AddByUrlTask;
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.GetFileListTask;
import org.transdroid.daemon.task.GetFileListTaskSuccessResult;
import org.transdroid.daemon.task.GetTorrentDetailsTask;
import org.transdroid.daemon.task.GetTorrentDetailsTaskSuccessResult;
import org.transdroid.daemon.task.RemoveTask;
import org.transdroid.daemon.task.RetrieveTask;
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 org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
/**
* An adapter that allows for easy access to rTorrent torrent data. Communication
* is handled via the XML-RPC protocol.
*
* @author erickok
*
*/
public class RtorrentAdapter implements IDaemonAdapter {
private static final String LOG_NAME = "rTorrent daemon";
private static final String DEFAULT_RPC_URL = "/RPC2";
private DaemonSettings settings;
private XMLRPCClient rpcclient;
public RtorrentAdapter(DaemonSettings settings) {
this.settings = settings;
}
@Override
public DaemonTaskResult executeTask(DaemonTask task) {
try {
switch (task.getMethod()) {
case Retrieve:
Object result = makeRtorrentCall("d.multicall", new String[] { "main", "d.get_hash=", "d.get_name=", "d.get_state=", "d.get_down_rate=", "d.get_up_rate=", "d.get_peers_connected=", "d.get_peers_not_connected=", "d.get_peers_accounted=", "d.get_bytes_done=", "d.get_up_total=", "d.get_size_bytes=", "d.get_creation_date=", "d.get_left_bytes=", "d.get_complete=", "d.is_active=", "d.is_hash_checking=", "d.get_base_path=", "d.get_base_filename=", "d.get_message=", "d.get_custom=addtime", "d.get_custom=seedingtime", "d.get_custom1=" });
return new RetrieveTaskSuccessResult((RetrieveTask) task, onTorrentsRetrieved(result),null);
case GetTorrentDetails:
Object dresult = makeRtorrentCall("t.multicall", new String[] { task.getTargetTorrent().getUniqueID(), "", "t.get_url=" });
return new GetTorrentDetailsTaskSuccessResult((GetTorrentDetailsTask) task, onTorrentDetailsRetrieved(dresult));
case GetFileList:
Object fresult = makeRtorrentCall("f.multicall", new String[] { task.getTargetTorrent().getUniqueID(), "", "f.get_path=", "f.get_size_bytes=", "f.get_priority=", "f.get_completed_chunks=", "f.get_size_chunks=", "f.get_priority=", "f.get_frozen_path=" });
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 = Base64.encodeBytes(bytes).length();
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);
case Pause:
// Pause a torrent
makeRtorrentCall("d.pause", new String[] { task.getTargetTorrent().getUniqueID() });
return new DaemonTaskSuccessResult(task);
case PauseAll:
// Resume all torrents
makeRtorrentCall("d.multicall", new String[] { "main", "d.pause=" } );
return new DaemonTaskSuccessResult(task);
case Resume:
// Resume a torrent
makeRtorrentCall("d.resume", new String[] { task.getTargetTorrent().getUniqueID() });
return new DaemonTaskSuccessResult(task);
case ResumeAll:
// Resume all torrents
makeRtorrentCall("d.multicall", new String[] { "main", "d.resume=" } );
return new DaemonTaskSuccessResult(task);
case Stop:
// Stop a torrent
makeRtorrentCall("d.stop", new String[] { task.getTargetTorrent().getUniqueID() });
return new DaemonTaskSuccessResult(task);
case StopAll:
// Stop all torrents
makeRtorrentCall("d.multicall", new String[] { "main", "d.stop=" } );
return new DaemonTaskSuccessResult(task);
case Start:
// Start a torrent
makeRtorrentCall("d.start", new String[] { task.getTargetTorrent().getUniqueID() });
return new DaemonTaskSuccessResult(task);
case StartAll:
// Start all torrents
makeRtorrentCall("d.multicall", new String[] { "main", "d.start=" } );
return new DaemonTaskSuccessResult(task);
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);
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);
case SetLabel:
SetLabelTask labelTask = (SetLabelTask) task;
makeRtorrentCall("d.set_custom1", new String[] { task.getTargetTorrent().getUniqueID(), labelTask.getNewLabel() });
return new DaemonTaskSuccessResult(task);
default:
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.MethodUnsupported, task.getMethod() + " is not supported by " + getType()));
}
} catch (DaemonException e) {
return new DaemonTaskFailureResult(task, e);
} catch (FileNotFoundException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.FileAccessError, e.toString()));
} catch (IOException e) {
return new DaemonTaskFailureResult(task, new DaemonException(ExceptionType.ConnectionError, e.toString()));
}
}
private Object makeRtorrentCall(String serverMethod, Object[] arguments) throws DaemonException {
// Initialise the HTTP client
if (rpcclient == null) {
initialise();
}
try {
String params = "";
for (Object arg : arguments) params += " " + arg.toString();
DLog.d(LOG_NAME, "Calling " + serverMethod + " with params [" + (params.length() > 300? params.substring(0, 300) + "...": params) + " ]");
return rpcclient.call(serverMethod, arguments);
} catch (XMLRPCException e) {
DLog.d(LOG_NAME, e.toString());
throw new DaemonException(ExceptionType.ConnectionError, "Error making call to " + serverMethod + " with params " + arguments.toString() + ": " + e.toString());
}
}
/**
* Instantiates a XML-RPC client with proper credentials.
* @throws DaemonException On conflicting settings (i.e. user authentication but no password or username provided)
*/
private void initialise() throws DaemonException {
this.rpcclient = new XMLRPCClient(HttpHelper.createStandardHttpClient(settings, true), buildWebUIUrl().trim());
}
/**
* Build the URL of rTorrent's XML-RPC location 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().equals("")? DEFAULT_RPC_URL: settings.getFolder());
}
private List<Torrent> onTorrentsRetrieved(Object response) throws DaemonException {
if (response == null || !(response instanceof Object[])) {
throw new DaemonException(ExceptionType.ParsingFailed, "Response on retrieveing torrents did not return a list of objects");
} else {
// Parse torrent list from response
// Formatted as Object[][], see http://libtorrent.rakshasa.no/wiki/RTorrentCommands#Download
// 'Labels' are supported in rTorrent as 'groups' that can become the 'active view';
// support for this is not trivial since it requires multiple calls to get all the info at best
// (if it is even feasible with the current approach)
List<Torrent> torrents = new ArrayList<Torrent>();
Object[] responseList = (Object[]) response;
for (int i = 0; i < responseList.length; i++) {
Object[] info = (Object[]) responseList[i];
String error = (String)info[18];
error = error.equals("")? null: error;
// Determine the time added
Date added = null;
Long addtime = null;
try {
addtime = Long.valueOf(((String) info[19]).trim());
} catch (NumberFormatException e) {
// 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')
added = new Date(addtime * 1000L);
else {
// rTorrent didn't have the addtime (missing plugin?): base it on creationtime instead
if (info[11] instanceof Long)
added = new Date((Long)info[11] * 1000L);
else
added = new Date((Integer)info[11] * 1000L);
}
// Determine the seeding time
Date finished = null;
Long seedingtime = null;
try {
seedingtime = Long.valueOf(((String) info[20]).trim());
} catch (NumberFormatException e) {
// 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')
finished = new Date(seedingtime * 1000L);
// Determine the label
String label = null;
try {
label = URLDecoder.decode((String)info[21], "UTF-8");
} catch (UnsupportedEncodingException e) {
}
if (info[3] instanceof Long) {
// rTorrent uses the i8 dialect which returns 64-bit integers
long rateDownload = (Long)info[3];
String basePath = (String)info[16];
torrents.add(new Torrent(
i,
(String)info[0], // hash
(String)info[1], // name
convertTorrentStatus((Long)info[2], (Long)info[13], (Long)info[14], (Long)info[15]), // status
basePath.substring(0, basePath.indexOf((String)info[17])), // locationDir
((Long)info[3]).intValue(), // rateDownload
((Long)info[4]).intValue(), // rateUpload
((Long)info[5]).intValue(), // peersGettingFromUs
((Long)info[5]).intValue(), // peersSendingToUs
((Long)info[5]).intValue(), // peersConnected
((Long)info[5]).intValue() + ((Long)info[6]).intValue(), // peersKnown
(rateDownload > 0? (int) (((Long)info[12]) / rateDownload): -1), // eta (bytes left / rate download, if rate > 0)
(Long)info[8], // downloadedEver
(Long)info[9], // uploadedEver
(Long)info[10], // totalSize
((Long)info[8]).floatValue() / ((Long)info[10]).floatValue(), // partDone
0f, // TODO: Add availability data
label, // See remark on rTorrent/groups above
added,
finished,
error));
} else {
// rTorrent uses the default dialect with 32-bit integers
int rateDownload = (Integer)info[3];
String basePath = (String)info[16];
torrents.add(new Torrent(
i,
(String)info[0], // hash
(String)info[1], // name
convertTorrentStatus(((Integer)info[2]).longValue(), ((Integer)info[13]).longValue(), ((Integer)info[14]).longValue(), ((Integer)info[15]).longValue()), // status
basePath.substring(0, basePath.indexOf((String)info[17])), // locationDir
rateDownload, // rateDownload
(Integer)info[4], // rateUpload
(Integer)info[5], // peersGettingFromUs
(Integer)info[5], // peersSendingToUs
(Integer)info[5], // peersConnected
(Integer)info[5] + (Integer)info[6], // peersKnown
(rateDownload > 0? (int) ((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
((Integer)info[8]).floatValue() / ((Integer)info[10]).floatValue(), // partDone
0f, // TODO: Add availability data
label, // See remark on rTorrent/groups above
added,
finished,
error));
}
}
return torrents;
}
}
private List<TorrentFile> onTorrentFilesRetrieved(Object response, Torrent torrent) throws DaemonException {
if (response == null || !(response instanceof Object[])) {
throw new DaemonException(ExceptionType.ParsingFailed, "Response on retrieveing torrent files did not return a list of objects");
} else {
// Parse torrent files from response
// Formatted as Object[][], see http://libtorrent.rakshasa.no/wiki/RTorrentCommands#Download
List<TorrentFile> files= new ArrayList<TorrentFile>();
Object[] responseList = (Object[]) response;
for (int i = 0; i < responseList.length; i++) {
Object[] info = (Object[]) responseList[i];
if (info[1] instanceof Long) {
// rTorrent uses the i8 dialect which returns 64-bit integers
Long size = (Long)info[1];
Long chunksDone = (Long)info[3];
Long chunksTotal = (Long)info[4];
Long priority = (Long)info[5];
files.add(new TorrentFile(
"" + i,
(String)info[0], // name
((String)info[6]).substring(torrent.getLocationDir().length()), // relativePath (= fullPath - torrent locationDir)
(String)info[6], // fullPath
size, // size
(long) (size * ((float)chunksDone / (float)chunksTotal)), // done
convertRtorrentPriority(priority.intValue()))); // priority
//(Long)info[2] has priority
} else {
// rTorrent uses the default dialect with 32-bit integers
Integer size = (Integer)info[1];
Integer chunksDone = (Integer)info[3];
Integer chunksTotal = (Integer)info[4];
Integer priority = (Integer)info[5];
files.add(new TorrentFile(
"" + i,
(String)info[0], // name
((String)info[6]).substring(torrent.getLocationDir().length()), // relativePath (= fullPath - torrent locationDir)
(String)info[0], // fullPath
size, // size
(int) (size * ((float)chunksDone / (float)chunksTotal)), // done
convertRtorrentPriority(priority))); // priority
//(Long)info[2] has priority
}
}
return files;
}
}
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;
}
}
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;
}
}
private TorrentStatus convertTorrentStatus(Long state, Long complete, Long active, Long checking) {
if (state == 0) {
return TorrentStatus.Queued;
} else if (active == 1) {
if (complete == 1) {
return TorrentStatus.Seeding;
} else {
return TorrentStatus.Downloading;
}
} else if (checking == 1) {
return TorrentStatus.Checking;
} else {
return TorrentStatus.Paused;
}
}
private TorrentDetails onTorrentDetailsRetrieved(Object response) throws DaemonException {
if (response == null || !(response instanceof Object[])) {
throw new DaemonException(ExceptionType.ParsingFailed, "Response on retrieveing trackers did not return a list of objects");
} else {
// Parse a torrent's trackers from response
// Formatted as Object[][], see http://libtorrent.rakshasa.no/wiki/RTorrentCommands#Download
List<String> trackers = new ArrayList<String>();
Object[] responseList = (Object[]) response;
try {
for (int i = 0; i < responseList.length; i++) {
Object[] info = (Object[]) responseList[i];
trackers.add((String) info[0]);
}
} catch (Exception e) {
DLog.e(LOG_NAME, e.toString());
}
return new TorrentDetails(trackers, null);
}
}
@Override
public Daemon getType() {
return settings.getType();
}
@Override
public DaemonSettings getSettings() {
return this.settings;
}
}
| Java |
/*
* This file is part of Transdroid <http://www.transdroid.org>
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
package org.transdroid.daemon;
import org.transdroid.daemon.task.DaemonTask;
import org.transdroid.daemon.task.DaemonTaskFailureResult;
import org.transdroid.daemon.task.DaemonTaskSuccessResult;
/**
* The required methods to implement by a class that wants to use a IDaemonAdapter instance.
*
* @author erickok
*
*/
public interface IDaemonCallback {
void onQueuedTaskStarted(DaemonTask started);
void onQueuedTaskFinished(DaemonTask finished);
void onQueueEmpty();
void onTaskFailure(DaemonTaskFailureResult result);
void onTaskSuccess(DaemonTaskSuccessResult result);
boolean isAttached();
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.