1
0
Fork 0
mirror of https://github.com/gsantner/dandelion synced 2024-11-25 13:52:08 +01:00

Let PodService fetch from DfA; PodSelection rework

This commit is contained in:
Gregor Santner 2016-10-05 02:30:10 +02:00
parent 160ed992df
commit 50207181f9
9 changed files with 2050 additions and 181 deletions

View file

@ -0,0 +1,470 @@
package com.github.dfa.diaspora_android.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by gsantner (https://gsantner.github.io/ on 30.09.16.
* DiasporaPodList - List container for DiasporaPod's, with methods to merge with other DiasporaPodLists
* DiasporaPod - Data container for a Pod, can include N DiasporaPodUrl's
* DiasporaPodUrl - A Url of an DiasporaPod
* For all Classes a loading and saving to JSON method is available
*/
public class DiasporaPodList implements Iterable<DiasporaPodList.DiasporaPod>, Serializable {
private List<DiasporaPod> pods = new ArrayList<>();
private boolean trackMergeChanges = false;
private Integer trackAddedIndexStart = -1;
private List<Integer> trackUpdatedIndexes = new ArrayList<>();
public DiasporaPodList() {
}
/**
* Load DiasporaPodList from Json
*
* @param json Json Object
*/
public DiasporaPodList fromJson(JSONObject json) throws JSONException {
JSONArray jarr;
pods.clear();
if (json.has("pods")) {
jarr = json.getJSONArray("pods");
for (int i = 0; i < jarr.length(); i++) {
DiasporaPod pod = new DiasporaPod().fromJson(jarr.getJSONObject(i));
pods.add(pod);
}
}
return this;
}
/**
* Convert DiasporaPodList to JSON
*/
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
JSONArray jpods = new JSONArray();
for (DiasporaPod pod : pods) {
jpods.put(pod.toJson());
}
json.put("pods", jpods);
return json;
}
/**
* Merge newer entries into this podlist
* Will add new pods, and update data of pods with data from the new list
*
* @param newPodList Another podlist
*/
public void mergeWithNewerEntries(final DiasporaPodList newPodList) throws JSONException {
if (isTrackMergeChanges()) {
trackAddedIndexStart = -1;
trackUpdatedIndexes.clear();
}
for (DiasporaPod newPod : newPodList) {
int index = pods.indexOf(newPod);
if (index >= 0) {
DiasporaPod updatePodBak = new DiasporaPod().fromJson(pods.get(index).toJson());
DiasporaPod updatePod = pods.get(index);
updatePod.fromJson(newPod.toJson());
// Restore Pod id (if was set to zero)
if (updatePodBak.getId() != 0 && updatePod.getId() == 0) {
updatePod.setId(updatePodBak.getId());
}
if (updatePodBak.getActive6() != 0 && updatePod.getActive6() == 0) {
updatePod.setActive6(updatePodBak.getActive6());
}
if (updatePodBak.getScore() != 0 && updatePod.getScore() == 0) {
updatePod.setScore(updatePodBak.getScore());
}
if (isTrackMergeChanges()) {
trackUpdatedIndexes.add(index);
}
} else {
pods.add(newPod);
if (isTrackMergeChanges() && trackAddedIndexStart == -1) {
trackAddedIndexStart = pods.size() - 1;
}
}
}
}
/**
* Sort the pod list
*/
public void sortPods() {
Collections.sort(pods);
}
/**
* Iterator for Iterable interface (forEach, ..)
*/
public Iterator<DiasporaPod> iterator() {
return pods.iterator();
}
public int size() {
return pods.size();
}
public int indexOf(DiasporaPod pod) {
return pods.indexOf(pod);
}
public List<DiasporaPod> getPods() {
return pods;
}
public void setPods(List<DiasporaPod> pods) {
this.pods = pods;
}
public DiasporaPod getPodAt(int index) {
if (index >= 0 && index < pods.size()) {
return pods.get(index);
}
return null;
}
public boolean isTrackMergeChanges() {
return trackMergeChanges;
}
public void setTrackMergeChanges(boolean trackMergeChanges) {
this.trackMergeChanges = trackMergeChanges;
}
public Integer getTrackAddedIndexStart() {
return trackAddedIndexStart;
}
public List<Integer> getTrackUpdatedIndexes() {
return trackUpdatedIndexes;
}
/*
*
*
*
*
* */
public static class DiasporaPod implements Iterable<DiasporaPodList.DiasporaPod.DiasporaPodUrl>, Comparable<DiasporaPod>, Serializable {
private List<DiasporaPodUrl> podUrls = new ArrayList<>();
private List<String> mainLangs = new ArrayList<>();
private String name = "";
private int score = 0;
private int id = 0;
private long active6 = 0;
public DiasporaPod() {
}
/**
* Load a DiasporaPod from JSON
*
* @param json Json Object
*/
public DiasporaPod fromJson(JSONObject json) throws JSONException {
JSONArray jarr;
if (json.has("name")) {
name = json.getString("name");
}
if (json.has("mainLangs")) {
jarr = json.getJSONArray("mainLangs");
for (int i = 0; i < jarr.length(); i++) {
String val = jarr.getString(i);
if (!mainLangs.contains(val)) {
mainLangs.add(val);
}
}
}
if (json.has("podUrls")) {
jarr = json.getJSONArray("podUrls");
for (int i = 0; i < jarr.length(); i++) {
DiasporaPodUrl podUrl = new DiasporaPodUrl().fromJson(jarr.getJSONObject(i));
if (!podUrls.contains(podUrl)) {
podUrls.add(podUrl);
}
}
}
if (json.has("score")) {
score = json.getInt("score");
}
if (json.has("active6")) {
active6 = json.getLong("active6");
}
if (json.has("id")) {
id = json.getInt("id");
}
return this;
}
/**
* Convert DiasporaPod to JSON
*/
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("score", score);
json.put("active6", active6);
json.put("id", id);
// Pod urls
JSONArray jarr = new JSONArray();
for (DiasporaPodUrl value : podUrls) {
jarr.put(value.toJson());
}
json.put("podUrls", jarr);
// main langs
jarr = new JSONArray();
for (String value : mainLangs) {
jarr.put(value);
}
json.put("mainLangs", jarr);
return json;
}
@Override
public boolean equals(Object o) {
boolean ret = false;
if (o instanceof DiasporaPod) {
DiasporaPod otherPod = (DiasporaPod) o;
// Check if id is equal
ret = this.id != 0 && this.id == otherPod.id;
// Check if host is the same (fallback if id is 0)
if (!ret) {
for (DiasporaPodUrl podUrl : podUrls) {
for (DiasporaPodUrl otherPodUrl : otherPod.getPodUrls()) {
if (podUrl.getBaseUrl().equals(otherPodUrl.getBaseUrl())) {
ret = true;
}
}
}
}
}
return ret;
}
@Override
public int compareTo(DiasporaPod otherPod) {
if (otherPod != null) {
List<DiasporaPodUrl> myPodUrls = getPodUrls();
List<DiasporaPodUrl> otherPodUrls = otherPod.getPodUrls();
if (!myPodUrls.isEmpty() && !otherPodUrls.isEmpty()) {
return myPodUrls.get(0).getHost().compareTo(otherPodUrls.get(0).getHost());
}
}
return name.compareTo(otherPod.getName());
}
@Override
public String toString() {
return name + "(" + id + ")";
}
/**
* Iterator for Iterable interface (forEach, ..)
*/
public Iterator<DiasporaPodUrl> iterator() {
return podUrls.iterator();
}
/*
* Getter & Setter
*/
public List<DiasporaPodUrl> getPodUrls() {
return podUrls;
}
public DiasporaPod setPodUrls(List<DiasporaPodUrl> podUrls) {
this.podUrls = podUrls;
return this;
}
public List<String> getMainLangs() {
return mainLangs;
}
public DiasporaPod setMainLangs(List<String> mainLangs) {
this.mainLangs = mainLangs;
return this;
}
public DiasporaPod appendMainLangs(String... values) {
for (String mainLang : values) {
this.mainLangs.add(mainLang);
}
return this;
}
public DiasporaPod appendPodUrls(DiasporaPodUrl... values) {
for (DiasporaPodUrl value : values) {
this.podUrls.add(value);
}
return this;
}
public String getName() {
return name;
}
public DiasporaPod setName(String name) {
this.name = name;
return this;
}
public int getScore() {
return score;
}
public DiasporaPod setScore(int score) {
this.score = score;
return this;
}
public long getActive6() {
return active6;
}
public DiasporaPod setActive6(long active6) {
this.active6 = active6;
return this;
}
public int getId() {
return id;
}
public DiasporaPod setId(int id) {
this.id = id;
return this;
}
/*
*
*
*
*
*
*/
public static class DiasporaPodUrl implements Serializable {
private String host = "";
private String protocol = "https";
private Integer port = 443;
public DiasporaPodUrl() {
}
public DiasporaPodUrl(JSONObject json) throws JSONException {
fromJson(json);
}
/**
* Get the base url
*
* @return
*/
public String getBaseUrl() {
return protocol + "://" + host + (isPortNeeded() ? port : "");
}
/**
* Convert JSON to DiasporaPodList
*
* @param json JSON Object
*/
public DiasporaPodUrl fromJson(JSONObject json) throws JSONException {
if (json.has("host")) {
host = json.getString("host");
}
if (json.has("protocol")) {
protocol = json.getString("protocol");
}
if (json.has("port")) {
port = json.getInt("port");
}
return this;
}
/***
* Convert DiasporaPodList to JSON
*/
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
json.put("host", host);
if (!protocol.equals("https")) {
json.put("protocol", protocol);
}
if (port != 443) {
json.put("port", port);
}
return json;
}
/**
* Tells if the ports needs to shown
*/
public boolean isPortNeeded() {
return !((port == 80 && protocol.equals("http")) || (port == 443 && protocol.equals("https")));
}
@Override
public String toString() {
return getBaseUrl();
}
@Override
public boolean equals(Object o) {
if (o instanceof DiasporaPodUrl) {
return getBaseUrl().equals(((DiasporaPodUrl) o).getBaseUrl());
}
return false;
}
/*
* GETTER & SETTER
*/
public String getHost() {
return host;
}
public DiasporaPodUrl setHost(String host) {
this.host = host;
return this;
}
public String getProtocol() {
return protocol;
}
public DiasporaPodUrl setProtocol(String protocol) {
this.protocol = protocol;
return this;
}
public Integer getPort() {
return port;
}
public DiasporaPodUrl setPort(Integer port) {
this.port = port;
return this;
}
}
}
}

View file

@ -10,9 +10,9 @@ import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.design.widget.Snackbar; import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable; import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.util.Linkify; import android.text.util.Linkify;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
@ -23,74 +23,94 @@ import android.view.ViewGroup;
import android.webkit.CookieManager; import android.webkit.CookieManager;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView; import android.widget.ListView;
import com.github.dfa.diaspora_android.App; import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R; import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.activity.MainActivity; import com.github.dfa.diaspora_android.activity.MainActivity;
import com.github.dfa.diaspora_android.data.AppSettings; import com.github.dfa.diaspora_android.data.AppSettings;
import com.github.dfa.diaspora_android.data.DiasporaPodList;
import com.github.dfa.diaspora_android.data.DiasporaPodList.DiasporaPod;
import com.github.dfa.diaspora_android.task.GetPodsService; import com.github.dfa.diaspora_android.task.GetPodsService;
import com.github.dfa.diaspora_android.util.AppLog; import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper; import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import com.github.dfa.diaspora_android.util.Helpers;
import com.github.dfa.diaspora_android.util.WebHelper; import com.github.dfa.diaspora_android.util.WebHelper;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
/** /**
* Fragment that lets the user choose a Pod * Fragment that lets the user choose a Pod
* Created by vanitas on 01.10.16. * Created by vanitas on 01.10.16.
*/ */
public class PodSelectionFragment extends CustomFragment { public class PodSelectionFragment extends CustomFragment implements SearchView.OnQueryTextListener {
public static final String TAG = "com.github.dfa.diaspora_android.PodSelectionFragment"; public static final String TAG = "com.github.dfa.diaspora_android.PodSelectionFragment";
protected EditText editFilter; @BindView(R.id.podselection__listpods)
protected ListView listPods; protected ListView listViewPod;
protected ImageView selectPodButton;
protected App app; protected App app;
protected AppSettings appSettings; protected AppSettings appSettings;
private DiasporaPodList podList;
private ArrayAdapter<String> listViewPodAdapter;
private String filterString = "";
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
AppLog.d(this, "onCreateView()"); AppLog.d(this, "onCreateView()");
return inflater.inflate(R.layout.podselection__fragment, container, false); View view = inflater.inflate(R.layout.podselection__fragment, container, false);
ButterKnife.bind(this, view);
return view;
} }
@Override @Override
public void onViewCreated(View view, Bundle savedInstanceState) { public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState); super.onViewCreated(view, savedInstanceState);
this.app = (App) getActivity().getApplication(); app = (App) getActivity().getApplication();
this.appSettings = app.getSettings(); appSettings = app.getSettings();
this.editFilter = (EditText) view.findViewById(R.id.podselection__edit_filter); // Load local podlist
this.listPods = (ListView) view.findViewById(R.id.podselection__listpods); podList = new DiasporaPodList();
this.selectPodButton = (ImageView) view.findViewById(R.id.podselection__button_select_pod); mergePodlistWithRessources(podList);
podList.setTrackMergeChanges(true);
updateListedPods();
listPods.setTextFilterEnabled(true);
listPods.setOnItemClickListener(new AdapterView.OnItemClickListener() { listViewPod.setTextFilterEnabled(true);
listViewPod.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override @Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
showPodConfirmationDialog((String) listPods.getAdapter().getItem(i)); showPodConfirmationDialog((String) listViewPod.getAdapter().getItem(i));
} }
}); });
setListedPods(appSettings.getPreviousPodlist());
LocalBroadcastManager.getInstance(getContext()).registerReceiver(podListReceiver, new IntentFilter(GetPodsService.MESSAGE_PODS_RECEIVED)); LocalBroadcastManager.getInstance(getContext()).registerReceiver(podListReceiver, new IntentFilter(GetPodsService.MESSAGE_PODS_RECEIVED));
if (!WebHelper.isOnline(getContext())) { Helpers.showInfoIfUserNotConnectedToInternet(getContext(), listViewPod);
Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show();
} }
selectPodButton.setOnClickListener(new View.OnClickListener() {
@Override public void mergePodlistWithRessources(DiasporaPodList podlist) {
public void onClick(View view) { String sPodlist = Helpers.readTextfileFromRawRessource(getContext(), R.raw.podlist, "", "");
if (editFilter.getText().length() > 4 && editFilter.getText().toString().contains("")) { try {
showPodConfirmationDialog(editFilter.getText().toString()); JSONObject jPodlist = new JSONObject(sPodlist);
} else { podlist.mergeWithNewerEntries(new DiasporaPodList().fromJson(jPodlist));
Snackbar.make(listPods, R.string.valid_pod, Snackbar.LENGTH_LONG).show(); } catch (JSONException e) {
e.printStackTrace();
} }
} }
});
// Called when a pod was clicked (or custom)
public void onPodButtonClicked(View v) {
//if (editFilter.getText().length() > 4 && editFilter.getText().toString().contains("")) {
showPodConfirmationDialog(filterString);
//} else {
// Snackbar.make(listViewPod, R.string.valid_pod, Snackbar.LENGTH_LONG).show();
//}
} }
@Override @Override
@ -111,15 +131,17 @@ public class PodSelectionFragment extends CustomFragment {
private final BroadcastReceiver podListReceiver = new BroadcastReceiver() { private final BroadcastReceiver podListReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("pods")) { if (intent.hasExtra(GetPodsService.EXTRA_PODLIST)) {
Bundle extras = intent.getExtras(); Bundle extras = intent.getExtras();
String[] pods = extras.getStringArray("pods"); DiasporaPodList newPods = (DiasporaPodList) extras.get(GetPodsService.EXTRA_PODLIST);
if (pods != null && pods.length > 0) { if (newPods != null && newPods.getPods().size() > 0) {
app.getSettings().setPreviousPodlist(pods); try {
setListedPods(pods); podList.mergeWithNewerEntries(newPods);
updateListedPods();
} catch (JSONException ignored) {
}
} else { } else {
setListedPods(app.getSettings().getPreviousPodlist()); Snackbar.make(listViewPod, R.string.podlist_error, Snackbar.LENGTH_SHORT).show();
Snackbar.make(listPods, R.string.podlist_error, Snackbar.LENGTH_SHORT).show();
} }
} }
} }
@ -132,38 +154,25 @@ public class PodSelectionFragment extends CustomFragment {
getContext().startService(i); getContext().startService(i);
} }
private void updateListedPods() {
private void setListedPods(String[] listedPodsArr) {
final ArrayList<String> listedPodsList = new ArrayList<>(); final ArrayList<String> listedPodsList = new ArrayList<>();
for (String pod : listedPodsArr) { for (DiasporaPod pod : this.podList) {
listedPodsList.add(pod.toLowerCase()); listedPodsList.add(pod.getPodUrls().get(0).getHost());
} }
final ArrayAdapter<String> adapter = new ArrayAdapter<>( listViewPodAdapter = new ArrayAdapter<>(
getContext(), getContext(),
android.R.layout.simple_list_item_1, android.R.layout.simple_list_item_1,
listedPodsList); listedPodsList);
// save index and top position // save index and top position
int index = listPods.getFirstVisiblePosition(); int index = listViewPod.getFirstVisiblePosition();
View v = listPods.getChildAt(0); View v = listViewPod.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - listPods.getPaddingTop()); int top = (v == null) ? 0 : (v.getTop() - listViewPod.getPaddingTop());
listPods.setAdapter(adapter); listViewPod.setAdapter(listViewPodAdapter);
listPods.setSelectionFromTop(index, top); listViewPod.setSelectionFromTop(index, top);
adapter.getFilter().filter(editFilter.getText()); listViewPodAdapter.getFilter().filter(filterString);
editFilter.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
(adapter).getFilter().filter(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
}
});
} }
private void showPodConfirmationDialog(final String selectedPod) { private void showPodConfirmationDialog(final String selectedPod) {
@ -173,7 +182,7 @@ public class PodSelectionFragment extends CustomFragment {
// Check if online // Check if online
if (!WebHelper.isOnline(getContext())) { if (!WebHelper.isOnline(getContext())) {
Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show(); Snackbar.make(listViewPod, R.string.no_internet, Snackbar.LENGTH_LONG).show();
return; return;
} }
@ -208,7 +217,7 @@ public class PodSelectionFragment extends CustomFragment {
e.printStackTrace(); e.printStackTrace();
} }
((MainActivity)getActivity()).openDiasporaUrl(new DiasporaUrlHelper(appSettings).getPodUrl()); ((MainActivity) getActivity()).openDiasporaUrl(new DiasporaUrlHelper(appSettings).getPodUrl());
} }
@Override @Override
@ -220,6 +229,13 @@ public class PodSelectionFragment extends CustomFragment {
@Override @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.podselection__menu, menu); inflater.inflate(R.menu.podselection__menu, menu);
MenuItem searchItem = menu.findItem(R.id.podselection__action_search);
if (searchItem != null) {
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(this);
}
super.onCreateOptionsMenu(menu, inflater); super.onCreateOptionsMenu(menu, inflater);
} }
@ -227,16 +243,26 @@ public class PodSelectionFragment extends CustomFragment {
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_reload: { case R.id.action_reload: {
if (WebHelper.isOnline(getContext())) { if (!Helpers.showInfoIfUserNotConnectedToInternet(getContext(), listViewPod)) {
Intent i = new Intent(getContext(), GetPodsService.class); Intent i = new Intent(getContext(), GetPodsService.class);
getContext().startService(i); getContext().startService(i);
return true; return true;
} else {
Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show();
return false;
} }
} }
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (listViewPodAdapter != null) {
(listViewPodAdapter).getFilter().filter(newText);
}
return true;
}
} }

View file

@ -24,9 +24,11 @@ import android.os.AsyncTask;
import android.os.IBinder; import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import com.github.dfa.diaspora_android.data.DiasporaPodList;
import com.github.dfa.diaspora_android.util.AppLog; import com.github.dfa.diaspora_android.util.AppLog;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -41,7 +43,9 @@ import javax.net.ssl.HttpsURLConnection;
import info.guardianproject.netcipher.NetCipher; import info.guardianproject.netcipher.NetCipher;
public class GetPodsService extends Service { public class GetPodsService extends Service {
public static final String EXTRA_PODLIST = "pods";
public static final String MESSAGE_PODS_RECEIVED = "com.github.dfa.diaspora.podsreceived"; public static final String MESSAGE_PODS_RECEIVED = "com.github.dfa.diaspora.podsreceived";
public static final String PODDY_PODLIST_URL = "https://raw.githubusercontent.com/Diaspora-for-Android/diaspora-android-extras/master/podList/podlist.json";
public GetPodsService() { public GetPodsService() {
} }
@ -53,75 +57,48 @@ public class GetPodsService extends Service {
} }
private void getPods() { private void getPods() {
/* AsyncTask<Void, Void, DiasporaPodList> getPodsAsync = new AsyncTask<Void, Void, DiasporaPodList>() {
* Most of the code in this AsyncTask is from the file getPodlistTask.java
* from the app "Diaspora Webclient".
* A few modifications and adaptations were made by me.
* Source:
* https://github.com/voidcode/Diaspora-Webclient/blob/master/src/com/voidcode/diasporawebclient/getPodlistTask.java
* Thanks to Terkel Sørensen ; License : GPLv3
*/
AsyncTask<Void, Void, String[]> getPodsAsync = new AsyncTask<Void, Void, String[]>() {
@Override @Override
protected String[] doInBackground(Void... params) { protected DiasporaPodList doInBackground(Void... params) {
StringBuilder sb = new StringBuilder();
// TODO: Update deprecated code BufferedReader br = null;
StringBuilder builder = new StringBuilder();
//HttpClient client = new DefaultHttpClient();
List<String> list = null;
HttpsURLConnection connection;
InputStream inStream;
try { try {
connection = NetCipher.getHttpsURLConnection("https://podupti.me/api.php?key=4r45tg&format=json"); HttpsURLConnection con = NetCipher.getHttpsURLConnection(PODDY_PODLIST_URL);
int statusCode = connection.getResponseCode(); if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) {
if (statusCode == 200) { br = new BufferedReader(new InputStreamReader(con.getInputStream()));
inStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inStream));
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = br.readLine()) != null) {
builder.append(line); sb.append(line);
} }
try { // Parse JSON & return pod list
inStream.close(); JSONObject json = new JSONObject(sb.toString());
} catch (IOException e) {/*Nothing to do*/} return new DiasporaPodList().fromJson(json);
connection.disconnect();
} else { } else {
AppLog.e(this, "Failed to download list of pods"); AppLog.e(this, "Failed to download list of pods");
} }
} catch (IOException e) { } catch (IOException | JSONException e) {
//TODO handle json buggy feed
e.printStackTrace(); e.printStackTrace();
} } finally {
//Parse the JSON Data if (br != null) {
try { try {
JSONObject jsonObjectAll = new JSONObject(builder.toString()); br.close();
JSONArray jsonArrayAll = jsonObjectAll.getJSONArray("pods"); } catch (IOException ignored) {
AppLog.d(this, "Number of entries " + jsonArrayAll.length()); }
list = new ArrayList<>(); }
for (int i = 0; i < jsonArrayAll.length(); i++) {
JSONObject jo = jsonArrayAll.getJSONObject(i);
if (jo.getString("secure").equals("true"))
list.add(jo.getString("domain"));
} }
} catch (Exception e) { // Could not fetch list of pods :(
//TODO Handle Parsing errors here return new DiasporaPodList();
e.printStackTrace();
}
if (list != null)
return list.toArray(new String[list.size()]);
else
return null;
} }
@Override @Override
protected void onPostExecute(String[] pods) { protected void onPostExecute(DiasporaPodList pods) {
if (pods == null) {
pods = new DiasporaPodList();
}
Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED); Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED);
broadcastIntent.putExtra("pods", pods != null ? pods : new String[0]); broadcastIntent.putExtra(EXTRA_PODLIST, pods);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
stopSelf(); stopSelf();
} }

View file

@ -26,8 +26,9 @@ import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment; import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.view.View;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R; import com.github.dfa.diaspora_android.R;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -130,4 +131,18 @@ public class Helpers {
} }
} }
} }
/**
* Show Information if user is offline, returns true if is not connected to internet
*
* @param context Context
* @param anchor A view anchor
*/
public static boolean showInfoIfUserNotConnectedToInternet(Context context, View anchor) {
boolean isOnline = WebHelper.isOnline(context);
if (!isOnline) {
Snackbar.make(anchor, R.string.no_internet, Snackbar.LENGTH_LONG).show();
}
return !isOnline;
}
} }

View file

@ -4,62 +4,29 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior" app:layout_behavior="@string/appbar_scrolling_view_behavior">
tools:showIn="@layout/podselection__fragment">
<Button
android:id="@+id/podselection__button_use_custom_pod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="@string/podselection__custom_pod"
tools:text="Benutzerdefinierter Pod" />
<ListView <ListView
android:id="@+id/podselection__listpods" android:id="@+id/podselection__listpods"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_above="@+id/podselection__podupti_notice" android:layout_alignParentBottom="true"
android:layout_below="@+id/podselection__edit_filter" android:layout_below="@+id/podselection__button_use_custom_pod"
android:choiceMode="singleChoice" /> android:choiceMode="singleChoice" />
<EditText
android:id="@+id/podselection__edit_filter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="@+id/textView"
android:layout_toStartOf="@+id/podselection__button_select_pod"
android:hint="@string/filter_hint"
android:inputType="textUri|textWebEditText" />
<ImageView
android:id="@+id/podselection__button_select_pod"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/podselection__listpods"
android:layout_alignEnd="@+id/podselection__listpods"
android:layout_alignTop="@+id/podselection__edit_filter"
android:contentDescription="@string/confirm_url"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="@drawable/ic_arrow_forward_black_48px" />
<TextView
android:id="@+id/podselection__podupti_notice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:autoLink="web"
android:text="@string/podlist_source_note"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/podselection__listpods"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="0dp"
android:gravity="center_vertical"
android:text="@string/prefix_https"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout> </RelativeLayout>

View file

@ -1,23 +1,27 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:id="@+id/recycler_view__list_item__root"
android:orientation="vertical"> android:orientation="vertical">
<View <View
android:id="@+id/recycler_view__list_item__divider"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="1dp" android:layout_height="1dp"
android:background="@color/divider"/> android:background="@color/divider" />
<TextView <TextView
android:id="@+id/recycler_view__list_item__text" android:id="@+id/recycler_view__list_item__text"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginStart="@dimen/activity_horizontal_margin"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp" android:layout_marginBottom="12dp"
android:textAppearance="@style/TextAppearance.AppCompat.Large" /> android:layout_marginEnd="@dimen/activity_horizontal_margin"
<View android:layout_marginStart="@dimen/activity_horizontal_margin"
android:layout_width="match_parent" android:layout_marginTop="12dp"
android:layout_height="1dp" android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:background="@color/divider"/> android:textColor="@color/primary_text"
tools:text="Very much text" />
</LinearLayout> </LinearLayout>

View file

@ -1,6 +1,13 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android" <menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"> xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/podselection__action_search"
android:icon="@drawable/ic_search_white_48px"
android:title="@string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView" />
<item <item
android:id="@+id/action_reload" android:id="@+id/action_reload"
android:icon="@drawable/ic_refresh_white_48px" android:icon="@drawable/ic_refresh_white_48px"

File diff suppressed because it is too large Load diff

View file

@ -34,6 +34,7 @@
<string name="title_activity_pods">Select Pod</string> <string name="title_activity_pods">Select Pod</string>
<string name="filter_hint">Enter pod domain</string> <string name="filter_hint">Enter pod domain</string>
<string name="confirm_url">Confirm pod url</string> <string name="confirm_url">Confirm pod url</string>
<string name="search_for_pod">Search for Pod…</string>
<string name="podlist_source_note">Note: The podlist is populated by secure pods listed on https://podupti.me. You can enter in the edit field any pod not listed.</string> <string name="podlist_source_note">Note: The podlist is populated by secure pods listed on https://podupti.me. You can enter in the edit field any pod not listed.</string>
<string name="valid_pod">Please enter a valid domain name</string> <string name="valid_pod">Please enter a valid domain name</string>
<string name="podlist_error">Error: Could not retrieve list of pods!</string> <string name="podlist_error">Error: Could not retrieve list of pods!</string>
@ -103,4 +104,5 @@
Diaspora. In the permissions section you can grant the \"write storage permission\".</string> Diaspora. In the permissions section you can grant the \"write storage permission\".</string>
<string name="permission_denied">Permission denied.</string> <string name="permission_denied">Permission denied.</string>
<string name="permission_granted_try_again">Permission granted. Please try again.</string> <string name="permission_granted_try_again">Permission granted. Please try again.</string>
<string name="podselection__custom_pod">Custom Pod</string>
</resources> </resources>