diff --git a/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaPodList.java b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaPodList.java new file mode 100644 index 00000000..194fcf38 --- /dev/null +++ b/app/src/main/java/com/github/dfa/diaspora_android/data/DiasporaPodList.java @@ -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, Serializable { + private List pods = new ArrayList<>(); + private boolean trackMergeChanges = false; + private Integer trackAddedIndexStart = -1; + private List 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 iterator() { + return pods.iterator(); + } + + public int size() { + return pods.size(); + } + + public int indexOf(DiasporaPod pod) { + return pods.indexOf(pod); + } + + public List getPods() { + return pods; + } + + public void setPods(List 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 getTrackUpdatedIndexes() { + return trackUpdatedIndexes; + } + + /* ██████╗ ██████╗ ██████╗ + * ██╔══██╗██╔═══██╗██╔══██╗ + * ██████╔╝██║ ██║██║ ██║ + * ██╔═══╝ ██║ ██║██║ ██║ + * ██║ ╚██████╔╝██████╔╝ + * ╚═╝ ╚═════╝ ╚═════╝ */ + public static class DiasporaPod implements Iterable, Comparable, Serializable { + private List podUrls = new ArrayList<>(); + private List 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 myPodUrls = getPodUrls(); + List 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 iterator() { + return podUrls.iterator(); + } + + /* + * Getter & Setter + */ + public List getPodUrls() { + return podUrls; + } + + public DiasporaPod setPodUrls(List podUrls) { + this.podUrls = podUrls; + return this; + } + + public List getMainLangs() { + return mainLangs; + } + + public DiasporaPod setMainLangs(List 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; + } + } + } +} diff --git a/app/src/main/java/com/github/dfa/diaspora_android/fragment/PodSelectionFragment.java b/app/src/main/java/com/github/dfa/diaspora_android/fragment/PodSelectionFragment.java index d833d271..accdfff2 100644 --- a/app/src/main/java/com/github/dfa/diaspora_android/fragment/PodSelectionFragment.java +++ b/app/src/main/java/com/github/dfa/diaspora_android/fragment/PodSelectionFragment.java @@ -10,9 +10,9 @@ import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; 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.TextWatcher; import android.text.util.Linkify; import android.view.LayoutInflater; import android.view.Menu; @@ -23,74 +23,94 @@ import android.view.ViewGroup; import android.webkit.CookieManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; -import android.widget.EditText; -import android.widget.ImageView; import android.widget.ListView; import com.github.dfa.diaspora_android.App; import com.github.dfa.diaspora_android.R; import com.github.dfa.diaspora_android.activity.MainActivity; 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.util.AppLog; 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 org.json.JSONException; +import org.json.JSONObject; + import java.util.ArrayList; +import butterknife.BindView; +import butterknife.ButterKnife; + /** * Fragment that lets the user choose a Pod * 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"; - protected EditText editFilter; - protected ListView listPods; - protected ImageView selectPodButton; + @BindView(R.id.podselection__listpods) + protected ListView listViewPod; protected App app; protected AppSettings appSettings; + private DiasporaPodList podList; + private ArrayAdapter listViewPodAdapter; + private String filterString = ""; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 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 public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - this.app = (App) getActivity().getApplication(); - this.appSettings = app.getSettings(); + app = (App) getActivity().getApplication(); + appSettings = app.getSettings(); - this.editFilter = (EditText) view.findViewById(R.id.podselection__edit_filter); - this.listPods = (ListView) view.findViewById(R.id.podselection__listpods); - this.selectPodButton = (ImageView) view.findViewById(R.id.podselection__button_select_pod); + // Load local podlist + podList = new DiasporaPodList(); + mergePodlistWithRessources(podList); + podList.setTrackMergeChanges(true); + updateListedPods(); - listPods.setTextFilterEnabled(true); - listPods.setOnItemClickListener(new AdapterView.OnItemClickListener() { + + listViewPod.setTextFilterEnabled(true); + listViewPod.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override 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)); - if (!WebHelper.isOnline(getContext())) { - Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show(); + Helpers.showInfoIfUserNotConnectedToInternet(getContext(), listViewPod); + } + + public void mergePodlistWithRessources(DiasporaPodList podlist) { + String sPodlist = Helpers.readTextfileFromRawRessource(getContext(), R.raw.podlist, "", ""); + try { + JSONObject jPodlist = new JSONObject(sPodlist); + podlist.mergeWithNewerEntries(new DiasporaPodList().fromJson(jPodlist)); + } catch (JSONException e) { + e.printStackTrace(); } - selectPodButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (editFilter.getText().length() > 4 && editFilter.getText().toString().contains("")) { - showPodConfirmationDialog(editFilter.getText().toString()); - } else { - Snackbar.make(listPods, R.string.valid_pod, Snackbar.LENGTH_LONG).show(); - } - } - }); + } + + // 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 @@ -111,15 +131,17 @@ public class PodSelectionFragment extends CustomFragment { private final BroadcastReceiver podListReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { - if (intent.hasExtra("pods")) { + if (intent.hasExtra(GetPodsService.EXTRA_PODLIST)) { Bundle extras = intent.getExtras(); - String[] pods = extras.getStringArray("pods"); - if (pods != null && pods.length > 0) { - app.getSettings().setPreviousPodlist(pods); - setListedPods(pods); + DiasporaPodList newPods = (DiasporaPodList) extras.get(GetPodsService.EXTRA_PODLIST); + if (newPods != null && newPods.getPods().size() > 0) { + try { + podList.mergeWithNewerEntries(newPods); + updateListedPods(); + } catch (JSONException ignored) { + } } else { - setListedPods(app.getSettings().getPreviousPodlist()); - Snackbar.make(listPods, R.string.podlist_error, Snackbar.LENGTH_SHORT).show(); + Snackbar.make(listViewPod, R.string.podlist_error, Snackbar.LENGTH_SHORT).show(); } } } @@ -132,38 +154,25 @@ public class PodSelectionFragment extends CustomFragment { getContext().startService(i); } - - private void setListedPods(String[] listedPodsArr) { + private void updateListedPods() { final ArrayList listedPodsList = new ArrayList<>(); - for (String pod : listedPodsArr) { - listedPodsList.add(pod.toLowerCase()); + for (DiasporaPod pod : this.podList) { + listedPodsList.add(pod.getPodUrls().get(0).getHost()); } - final ArrayAdapter adapter = new ArrayAdapter<>( + listViewPodAdapter = new ArrayAdapter<>( getContext(), android.R.layout.simple_list_item_1, listedPodsList); // save index and top position - int index = listPods.getFirstVisiblePosition(); - View v = listPods.getChildAt(0); - int top = (v == null) ? 0 : (v.getTop() - listPods.getPaddingTop()); - listPods.setAdapter(adapter); - listPods.setSelectionFromTop(index, top); + int index = listViewPod.getFirstVisiblePosition(); + View v = listViewPod.getChildAt(0); + int top = (v == null) ? 0 : (v.getTop() - listViewPod.getPaddingTop()); + listViewPod.setAdapter(listViewPodAdapter); + listViewPod.setSelectionFromTop(index, top); - adapter.getFilter().filter(editFilter.getText()); - 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) { - } - }); + listViewPodAdapter.getFilter().filter(filterString); } private void showPodConfirmationDialog(final String selectedPod) { @@ -173,7 +182,7 @@ public class PodSelectionFragment extends CustomFragment { // Check if online 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; } @@ -208,7 +217,7 @@ public class PodSelectionFragment extends CustomFragment { e.printStackTrace(); } - ((MainActivity)getActivity()).openDiasporaUrl(new DiasporaUrlHelper(appSettings).getPodUrl()); + ((MainActivity) getActivity()).openDiasporaUrl(new DiasporaUrlHelper(appSettings).getPodUrl()); } @Override @@ -220,6 +229,13 @@ public class PodSelectionFragment extends CustomFragment { @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 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); } @@ -227,16 +243,26 @@ public class PodSelectionFragment extends CustomFragment { public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_reload: { - if (WebHelper.isOnline(getContext())) { + if (!Helpers.showInfoIfUserNotConnectedToInternet(getContext(), listViewPod)) { Intent i = new Intent(getContext(), GetPodsService.class); getContext().startService(i); return true; - } else { - Snackbar.make(listPods, R.string.no_internet, Snackbar.LENGTH_LONG).show(); - return false; } } } 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; + } +} \ No newline at end of file diff --git a/app/src/main/java/com/github/dfa/diaspora_android/task/GetPodsService.java b/app/src/main/java/com/github/dfa/diaspora_android/task/GetPodsService.java index afce5e01..988d3cf0 100644 --- a/app/src/main/java/com/github/dfa/diaspora_android/task/GetPodsService.java +++ b/app/src/main/java/com/github/dfa/diaspora_android/task/GetPodsService.java @@ -24,9 +24,11 @@ import android.os.AsyncTask; import android.os.IBinder; import android.support.v4.content.LocalBroadcastManager; +import com.github.dfa.diaspora_android.data.DiasporaPodList; import com.github.dfa.diaspora_android.util.AppLog; import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; @@ -41,7 +43,9 @@ import javax.net.ssl.HttpsURLConnection; import info.guardianproject.netcipher.NetCipher; 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 PODDY_PODLIST_URL = "https://raw.githubusercontent.com/Diaspora-for-Android/diaspora-android-extras/master/podList/podlist.json"; public GetPodsService() { } @@ -53,75 +57,48 @@ public class GetPodsService extends Service { } private void getPods() { - /* - * 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 getPodsAsync = new AsyncTask() { + AsyncTask getPodsAsync = new AsyncTask() { @Override - protected String[] doInBackground(Void... params) { - - // TODO: Update deprecated code - - StringBuilder builder = new StringBuilder(); - //HttpClient client = new DefaultHttpClient(); - List list = null; - HttpsURLConnection connection; - InputStream inStream; + protected DiasporaPodList doInBackground(Void... params) { + StringBuilder sb = new StringBuilder(); + BufferedReader br = null; try { - connection = NetCipher.getHttpsURLConnection("https://podupti.me/api.php?key=4r45tg&format=json"); - int statusCode = connection.getResponseCode(); - if (statusCode == 200) { - inStream = connection.getInputStream(); - BufferedReader reader = new BufferedReader( - new InputStreamReader(inStream)); + HttpsURLConnection con = NetCipher.getHttpsURLConnection(PODDY_PODLIST_URL); + if (con.getResponseCode() == HttpsURLConnection.HTTP_OK) { + br = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; - while ((line = reader.readLine()) != null) { - builder.append(line); + while ((line = br.readLine()) != null) { + sb.append(line); } - try { - inStream.close(); - } catch (IOException e) {/*Nothing to do*/} - - connection.disconnect(); + // Parse JSON & return pod list + JSONObject json = new JSONObject(sb.toString()); + return new DiasporaPodList().fromJson(json); } else { AppLog.e(this, "Failed to download list of pods"); } - } catch (IOException e) { - //TODO handle json buggy feed + } catch (IOException | JSONException e) { e.printStackTrace(); - } - //Parse the JSON Data - try { - JSONObject jsonObjectAll = new JSONObject(builder.toString()); - JSONArray jsonArrayAll = jsonObjectAll.getJSONArray("pods"); - 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")); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException ignored) { + } } - - } catch (Exception e) { - //TODO Handle Parsing errors here - e.printStackTrace(); } - if (list != null) - return list.toArray(new String[list.size()]); - else - return null; + + // Could not fetch list of pods :( + return new DiasporaPodList(); } @Override - protected void onPostExecute(String[] pods) { + protected void onPostExecute(DiasporaPodList pods) { + if (pods == null) { + pods = new DiasporaPodList(); + } 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); stopSelf(); } diff --git a/app/src/main/java/com/github/dfa/diaspora_android/util/Helpers.java b/app/src/main/java/com/github/dfa/diaspora_android/util/Helpers.java index 830380ec..b31299e2 100644 --- a/app/src/main/java/com/github/dfa/diaspora_android/util/Helpers.java +++ b/app/src/main/java/com/github/dfa/diaspora_android/util/Helpers.java @@ -26,8 +26,9 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; 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 java.io.BufferedReader; @@ -72,7 +73,7 @@ public class Helpers { // Create an image file name String timeStamp = new SimpleDateFormat("dd-MM-yy_HH-mm", Locale.getDefault()).format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; - AppLog.d(Helpers.class, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); + AppLog.d(Helpers.class, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); File storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES); return new File( @@ -116,18 +117,32 @@ public class Helpers { public static void printBundle(Bundle savedInstanceState, String k) { if (savedInstanceState != null) { for (String key : savedInstanceState.keySet()) { - AppLog.d("SAVED", key + " is a key in the bundle " + k); + AppLog.d("SAVED", key + " is a key in the bundle " + k); Object bun = savedInstanceState.get(key); if (bun != null) { if (bun instanceof Bundle) { printBundle((Bundle) bun, k + "." + key); } else if (bun instanceof byte[]) { - AppLog.d("SAVED", "Key: " + k + "." + key + ": " + Arrays.toString((byte[]) bun)); + AppLog.d("SAVED", "Key: " + k + "." + key + ": " + Arrays.toString((byte[]) bun)); } else { - AppLog.d("SAVED", "Key: " + k + "." + key + ": " + bun.toString()); + AppLog.d("SAVED", "Key: " + k + "." + key + ": " + bun.toString()); } } } } } + + /** + * 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; + } } diff --git a/app/src/main/res/layout/podselection__fragment.xml b/app/src/main/res/layout/podselection__fragment.xml index b8e39ac4..7fabd3b2 100644 --- a/app/src/main/res/layout/podselection__fragment.xml +++ b/app/src/main/res/layout/podselection__fragment.xml @@ -4,62 +4,29 @@ xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" + android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" - app:layout_behavior="@string/appbar_scrolling_view_behavior" - tools:showIn="@layout/podselection__fragment"> + app:layout_behavior="@string/appbar_scrolling_view_behavior"> + +