Some cleaning

This commit is contained in:
Thomas 2020-12-07 09:04:44 +01:00
parent 555f108853
commit 62467a3fe1
18 changed files with 438 additions and 456 deletions

View File

@ -18,16 +18,16 @@
package org.eu.exodus_privacy.exodusprivacy; package org.eu.exodus_privacy.exodusprivacy;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Settings; import android.provider.Settings;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater; import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.SearchView; import android.widget.SearchView;
@ -57,7 +57,6 @@ public class MainActivity extends AppCompatActivity {
private List<Updatable> fragments; private List<Updatable> fragments;
private SearchView searchView; private SearchView searchView;
private Menu toolbarMenu; private Menu toolbarMenu;
private MenuItem settingsMenuItem;
private String packageName; private String packageName;
private MainBinding binding; private MainBinding binding;
private ApplicationListAdapter.OnAppClickListener onAppClickListener; private ApplicationListAdapter.OnAppClickListener onAppClickListener;
@ -65,23 +64,25 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.main); binding = DataBindingUtil.setContentView(this, R.layout.main);
final MainBinding mainBinding = binding; final MainBinding mainBinding = binding;
getSupportActionBar().setTitle(R.string.app_title); if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(R.string.app_title);
}
fragments = new ArrayList<>(); fragments = new ArrayList<>();
NetworkListener networkListener = new NetworkListener() { NetworkListener networkListener = new NetworkListener() {
@Override @Override
public void onSuccess() { public void onSuccess() {
runOnUiThread(() -> { runOnUiThread(() -> {
for(Updatable updatable : fragments){ for (Updatable updatable : fragments) {
if(updatable instanceof ReportFragment) { if (updatable instanceof ReportFragment) {
ApplicationViewModel model = ((ReportFragment) updatable).getModel(); ApplicationViewModel model = ((ReportFragment) updatable).getModel();
if(model.versionName == null) if (model.versionName == null)
model.report = DatabaseManager.getInstance(MainActivity.this).getReportFor(model.packageName, model.versionCode, model.source); model.report = DatabaseManager.getInstance(MainActivity.this).getReportFor(model.packageName, model.versionCode, model.source);
else else
model.report = DatabaseManager.getInstance(MainActivity.this).getReportFor(model.packageName,model.versionName,model.source); model.report = DatabaseManager.getInstance(MainActivity.this).getReportFor(model.packageName, model.versionName, model.source);
if(model.report != null) if (model.report != null)
model.trackers = DatabaseManager.getInstance(MainActivity.this).getTrackers(model.report.trackers); model.trackers = DatabaseManager.getInstance(MainActivity.this).getTrackers(model.report.trackers);
} }
updatable.onUpdateComplete(); updatable.onUpdateComplete();
@ -92,10 +93,10 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
public void onError(String error) { public void onError(String error) {
runOnUiThread(() -> { runOnUiThread(() -> {
for(Updatable updatable : fragments){ for (Updatable updatable : fragments) {
updatable.onUpdateComplete(); updatable.onUpdateComplete();
} }
Snackbar bar = Snackbar.make(mainBinding.fragmentContainer,error,Snackbar.LENGTH_LONG); Snackbar bar = Snackbar.make(mainBinding.fragmentContainer, error, Snackbar.LENGTH_LONG);
bar.show(); bar.show();
}); });
} }
@ -113,7 +114,7 @@ public class MainActivity extends AppCompatActivity {
FragmentManager manager = getSupportFragmentManager(); FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction(); FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_left) transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_left)
.replace(R.id.fragment_container,tracker) .replace(R.id.fragment_container, tracker)
.addToBackStack(null) .addToBackStack(null)
.commit(); .commit();
}; };
@ -123,12 +124,12 @@ public class MainActivity extends AppCompatActivity {
PackageManager pm = getPackageManager(); PackageManager pm = getPackageManager();
PackageInfo packageInfo = pm.getPackageInfo(vm.packageName, PackageManager.GET_PERMISSIONS); PackageInfo packageInfo = pm.getPackageInfo(vm.packageName, PackageManager.GET_PERMISSIONS);
ReportFragment report = ReportFragment.newInstance(pm,vm,packageInfo,onTrackerClickListener); ReportFragment report = ReportFragment.newInstance(pm, vm, packageInfo, onTrackerClickListener);
fragments.add(report); fragments.add(report);
FragmentManager manager = getSupportFragmentManager(); FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction(); FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_left) transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_left)
.replace(R.id.fragment_container,report) .replace(R.id.fragment_container, report)
.addToBackStack(null) .addToBackStack(null)
.commit(); .commit();
@ -137,7 +138,7 @@ public class MainActivity extends AppCompatActivity {
searchView.clearFocus(); searchView.clearFocus();
if (toolbarMenu != null) if (toolbarMenu != null)
(toolbarMenu.findItem(R.id.action_filter)).collapseActionView(); (toolbarMenu.findItem(R.id.action_filter)).collapseActionView();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null; assert imm != null;
imm.hideSoftInputFromWindow(mainBinding.fragmentContainer.getWindowToken(), 0); imm.hideSoftInputFromWindow(mainBinding.fragmentContainer.getWindowToken(), 0);
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
@ -153,8 +154,8 @@ public class MainActivity extends AppCompatActivity {
FragmentManager manager = getSupportFragmentManager(); FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction(); FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,home) transaction.replace(R.id.fragment_container, home)
.commit(); .commit();
home.startRefresh(); home.startRefresh();
} }
@ -164,7 +165,7 @@ public class MainActivity extends AppCompatActivity {
finish(); finish();
else { else {
getSupportFragmentManager().popBackStack(); getSupportFragmentManager().popBackStack();
fragments.remove(fragments.size()-1); fragments.remove(fragments.size() - 1);
} }
} }
@ -192,24 +193,21 @@ public class MainActivity extends AppCompatActivity {
} }
}); });
settingsMenuItem = menu.findItem(R.id.action_settings); MenuItem settingsMenuItem = menu.findItem(R.id.action_settings);
Updatable fragment = fragments.get(fragments.size()-1); Updatable fragment = fragments.get(fragments.size() - 1);
if (fragment instanceof ReportFragment) settingsMenuItem.setVisible(fragment instanceof ReportFragment);
settingsMenuItem.setVisible(true);
else
settingsMenuItem.setVisible(false);
return true; return true;
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_settings) { if (item.getItemId() == R.id.action_settings) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package",packageName,null)); intent.setData(Uri.fromParts("package", packageName, null));
try { try {
startActivity(intent); startActivity(intent);
} catch(android.content.ActivityNotFoundException e) { } catch (android.content.ActivityNotFoundException e) {
Snackbar bar = Snackbar.make(binding.fragmentContainer,R.string.no_settings,Snackbar.LENGTH_LONG); Snackbar bar = Snackbar.make(binding.fragmentContainer, R.string.no_settings, Snackbar.LENGTH_LONG);
bar.show(); bar.show();
} }
return true; return true;

View File

@ -2,7 +2,6 @@ package org.eu.exodus_privacy.exodusprivacy;
import android.content.Context; import android.content.Context;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.view.View;
import androidx.databinding.BaseObservable; import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable; import androidx.databinding.Bindable;
@ -17,7 +16,7 @@ import java.text.SimpleDateFormat;
public class ReportViewModel extends BaseObservable { public class ReportViewModel extends BaseObservable {
private ReportDisplay reportDisplay; private ReportDisplay reportDisplay;
public void setReportDisplay(ReportDisplay report){ public void setReportDisplay(ReportDisplay report) {
this.reportDisplay = report; this.reportDisplay = report;
notifyChange(); notifyChange();
} }
@ -54,8 +53,8 @@ public class ReportViewModel extends BaseObservable {
@Bindable @Bindable
public boolean getHasPermissionDangerous() { public boolean getHasPermissionDangerous() {
for(Permission perm : reportDisplay.permissions) { for (Permission perm : reportDisplay.permissions) {
if(perm.dangerous) if (perm.dangerous)
return true; return true;
} }
return false; return false;
@ -85,7 +84,7 @@ public class ReportViewModel extends BaseObservable {
String creator = reportDisplay.creator != null ? reportDisplay.creator : ""; String creator = reportDisplay.creator != null ? reportDisplay.creator : "";
if (reportDisplay.report != null && !reportDisplay.report.downloads.isEmpty()) { if (reportDisplay.report != null && !reportDisplay.report.downloads.isEmpty()) {
String download = reportDisplay.report.downloads; String download = reportDisplay.report.downloads;
download = download.replace("downloads",context.getString(R.string.downloads)); download = download.replace("downloads", context.getString(R.string.downloads));
creator += " (" + download + ")"; creator += " (" + download + ")";
} }
return creator; return creator;
@ -103,7 +102,7 @@ public class ReportViewModel extends BaseObservable {
@Bindable @Bindable
public String getReportVersion() { public String getReportVersion() {
if(reportDisplay.report != null) { if (reportDisplay.report != null) {
if (reportDisplay.versionName != null && !reportDisplay.report.version.equals(reportDisplay.versionName)) { if (reportDisplay.versionName != null && !reportDisplay.report.version.equals(reportDisplay.versionName)) {
return reportDisplay.report.version; return reportDisplay.report.version;
} else if (reportDisplay.versionName == null && reportDisplay.report.versionCode != reportDisplay.versionCode) { } else if (reportDisplay.versionName == null && reportDisplay.report.versionCode != reportDisplay.versionCode) {
@ -125,30 +124,30 @@ public class ReportViewModel extends BaseObservable {
public String getReportDate(Context context) { public String getReportDate(Context context) {
String reportDate = ""; String reportDate = "";
if(reportDisplay.report == null) if (reportDisplay.report == null)
return reportDate; return reportDate;
DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.LONG); DateFormat dateFormat = SimpleDateFormat.getDateInstance(DateFormat.LONG);
reportDate = context.getString(R.string.created_date)+" "+dateFormat.format(reportDisplay.report.creationDate.getTime()); reportDate = context.getString(R.string.created_date) + " " + dateFormat.format(reportDisplay.report.creationDate.getTime());
if (reportDisplay.report.creationDate.getTime().compareTo(reportDisplay.report.updateDate.getTime())!=0) if (reportDisplay.report.creationDate.getTime().compareTo(reportDisplay.report.updateDate.getTime()) != 0)
reportDate += " "+context.getString(R.string.and_updated)+" "+dateFormat.format(reportDisplay.report.updateDate.getTime())+"."; reportDate += " " + context.getString(R.string.and_updated) + " " + dateFormat.format(reportDisplay.report.updateDate.getTime()) + ".";
return reportDate; return reportDate;
} }
public String getCodeSignatureInfo(Context context) { public String getCodeSignatureInfo(Context context) {
if(reportDisplay.trackers != null && reportDisplay.trackers.size() > 0) if (reportDisplay.trackers != null && reportDisplay.trackers.size() > 0)
return context.getString(R.string.code_signature_found); return context.getString(R.string.code_signature_found);
else if(reportDisplay.trackers != null) else if (reportDisplay.trackers != null)
return context.getString(R.string.code_signature_not_found); return context.getString(R.string.code_signature_not_found);
else else
return ""; return "";
} }
public String getCodePermissionInfo(Context context) { public String getCodePermissionInfo(Context context) {
if(reportDisplay.permissions != null && reportDisplay.permissions.size() > 0) if (reportDisplay.permissions != null && reportDisplay.permissions.size() > 0)
return context.getString(R.string.code_permission_found); return context.getString(R.string.code_permission_found);
else if(reportDisplay.permissions != null) else if (reportDisplay.permissions != null)
return context.getString(R.string.code_permission_not_found); return context.getString(R.string.code_permission_not_found);
else else
return ""; return "";
@ -158,7 +157,7 @@ public class ReportViewModel extends BaseObservable {
private int getColor(int number) { private int getColor(int number) {
if (number == 0) if (number == 0)
return R.drawable.square_green; return R.drawable.square_green;
else if(number < 5) else if (number < 5)
return R.drawable.square_light_yellow; return R.drawable.square_light_yellow;
else else
return R.drawable.square_light_red; return R.drawable.square_light_red;
@ -174,5 +173,4 @@ public class ReportViewModel extends BaseObservable {
} }
} }

View File

@ -34,7 +34,7 @@ public class Utils {
builder.append(packageName); builder.append(packageName);
for(Signature signature: signatures) { for (Signature signature : signatures) {
InputStream input = new ByteArrayInputStream(signature.toByteArray()); InputStream input = new ByteArrayInputStream(signature.toByteArray());
CertificateFactory cf = null; CertificateFactory cf = null;
try { try {
@ -92,18 +92,18 @@ public class Utils {
ArrayList<String> listStarter = new ArrayList<>(); ArrayList<String> listStarter = new ArrayList<>();
ArrayList<String> formatStarter = new ArrayList<>(); ArrayList<String> formatStarter = new ArrayList<>();
ArrayList<String> closeTags = new ArrayList<>(); ArrayList<String> closeTags = new ArrayList<>();
for(String line : lines) { for (String line : lines) {
if (line.matches("^#{1,5} .*")) { if (line.matches("^#{1,5} .*")) {
int nb = line.indexOf(" "); int nb = line.indexOf(" ");
String hx = "<h"+nb+">"; String hx = "<h" + nb + ">";
String endhx = "</h"+nb+">"; String endhx = "</h" + nb + ">";
builder.append(hx); builder.append(hx);
closeTags.add(endhx); closeTags.add(endhx);
line = line.substring(line.indexOf(" ")+1); line = line.substring(line.indexOf(" ") + 1);
} else if (line.matches("^ *[+\\-*] .*")) { } else if (line.matches("^ *[+\\-*] .*")) {
String starter=""; String starter = "";
if (listStarter.size() > 0 && line.startsWith(listStarter.get(listStarter.size()-1))) { if (listStarter.size() > 0 && line.startsWith(listStarter.get(listStarter.size() - 1))) {
starter = listStarter.get(listStarter.size()-1); starter = listStarter.get(listStarter.size() - 1);
} else { } else {
Pattern pattern = Pattern.compile("^( *[+\\-*] )"); Pattern pattern = Pattern.compile("^( *[+\\-*] )");
Matcher matcher = pattern.matcher(line); Matcher matcher = pattern.matcher(line);
@ -115,19 +115,22 @@ public class Utils {
} }
} }
builder.append("<li> "); builder.append("<li> ");
int beginIndex = line.indexOf(starter)+starter.length(); int beginIndex = 0;
if (starter != null) {
beginIndex = line.indexOf(starter) + starter.length();
}
line = line.substring(beginIndex); line = line.substring(beginIndex);
closeTags.add("</li>"); closeTags.add("</li>");
} else { } else {
while(!listStarter.isEmpty()) { while (!listStarter.isEmpty()) {
listStarter.remove(listStarter.size() - 1); listStarter.remove(listStarter.size() - 1);
builder.append("</ul>\n"); builder.append("</ul>\n");
} }
builder.append("<p>"); builder.append("<p>");
closeTags.add("</p>"); closeTags.add("</p>");
} }
while(!line.isEmpty()){ while (!line.isEmpty()) {
Pattern pattern = Pattern.compile("^\\[(.+?)(?=\\]\\()\\]\\((http.+?)(?=\\))\\)"); Pattern pattern = Pattern.compile("^\\[(.+?)(?=]\\()]\\((http.+?)(?=\\))\\)");
//Pattern pattern = Pattern.compile("^\\[(.*)\\]\\((http.*)\\)"); //Pattern pattern = Pattern.compile("^\\[(.*)\\]\\((http.*)\\)");
Matcher matcher = pattern.matcher(line); Matcher matcher = pattern.matcher(line);
if (matcher.find()) { if (matcher.find()) {
@ -136,7 +139,7 @@ public class Utils {
builder.append("\">"); builder.append("\">");
builder.append(matcher.group(1)); builder.append(matcher.group(1));
builder.append("</a>"); builder.append("</a>");
line = line.substring(line.indexOf(")")+1); line = line.substring(line.indexOf(")") + 1);
continue; continue;
} }
pattern = Pattern.compile("^(http.*)"); pattern = Pattern.compile("^(http.*)");
@ -147,44 +150,45 @@ public class Utils {
builder.append("\">"); builder.append("\">");
builder.append(matcher.group(1)); builder.append(matcher.group(1));
builder.append("</a>"); builder.append("</a>");
line = line.substring(matcher.group(1).length()); String sub = matcher.group(1);
if (sub != null) {
line = line.substring(sub.length());
}
continue; continue;
} }
pattern = Pattern.compile("^[*_]{2}(.+)[*_]{2}"); pattern = Pattern.compile("^[*_]{2}(.+)[*_]{2}");
matcher = pattern.matcher(line); matcher = pattern.matcher(line);
if (matcher.find()) { if (matcher.find()) {
if(line.startsWith("*")) { if (line.startsWith("*")) {
line = line.replaceFirst("\\*\\*", "<b>"); line = line.replaceFirst("\\*\\*", "<b>");
formatStarter.add("**"); formatStarter.add("**");
} } else {
else {
line = line.replaceFirst("__", "<b>"); line = line.replaceFirst("__", "<b>");
formatStarter.add("__"); formatStarter.add("__");
} }
continue; continue;
} }
pattern = Pattern.compile("^[*_]{1}(.+)"); pattern = Pattern.compile("^[*_](.+)");
matcher = pattern.matcher(line); matcher = pattern.matcher(line);
if (matcher.find()) { if (matcher.find()) {
if(line.startsWith("*")) { if (line.startsWith("*")) {
line = line.replaceFirst("\\*", "<i>"); line = line.replaceFirst("\\*", "<i>");
formatStarter.add("*"); formatStarter.add("*");
} } else {
else {
line = line.replaceFirst("_", "<i>"); line = line.replaceFirst("_", "<i>");
formatStarter.add("_"); formatStarter.add("_");
} }
continue; continue;
} }
if(formatStarter.size() > 0) { if (formatStarter.size() > 0) {
String checkFormat; String checkFormat;
if(line.contains(" ")) if (line.contains(" "))
checkFormat = line.substring(0,line.indexOf(" ")); checkFormat = line.substring(0, line.indexOf(" "));
else else
checkFormat = line; checkFormat = line;
String lastFormat = formatStarter.get(formatStarter.size()-1); String lastFormat = formatStarter.get(formatStarter.size() - 1);
if (checkFormat.contains(lastFormat)) { if (checkFormat.contains(lastFormat)) {
if(lastFormat.length()==2) { if (lastFormat.length() == 2) {
if (lastFormat.contains("*")) if (lastFormat.contains("*"))
line = line.replaceFirst("\\*\\*", "</b>"); line = line.replaceFirst("\\*\\*", "</b>");
else else
@ -195,12 +199,12 @@ public class Utils {
else else
line = line.replaceFirst("_", "</i>"); line = line.replaceFirst("_", "</i>");
} }
formatStarter.remove(formatStarter.size()-1); formatStarter.remove(formatStarter.size() - 1);
continue; continue;
} }
} }
if(line.contains(" ")) { if (line.contains(" ")) {
builder.append(line.substring(0, line.indexOf(" ") + 1)); builder.append(line.substring(0, line.indexOf(" ") + 1));
line = line.substring(line.indexOf(" ") + 1); line = line.substring(line.indexOf(" ") + 1);
} else { } else {
@ -209,13 +213,13 @@ public class Utils {
} }
} }
//close all unclosed tags starting at the end //close all unclosed tags starting at the end
while(!closeTags.isEmpty()) { while (!closeTags.isEmpty()) {
builder.append(closeTags.remove(closeTags.size()-1)); builder.append(closeTags.remove(closeTags.size() - 1));
} }
builder.append("\n"); builder.append("\n");
} }
while(!listStarter.isEmpty()) { while (!listStarter.isEmpty()) {
listStarter.remove(listStarter.size() - 1); listStarter.remove(listStarter.size() - 1);
builder.append("</ul>\n"); builder.append("</ul>\n");
} }

View File

@ -40,44 +40,40 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class ApplicationListAdapter extends RecyclerView.Adapter { public class ApplicationListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ApplicationViewModel> applicationViewModels; private final OnAppClickListener onAppClickListener;
private OnAppClickListener onAppClickListener;
private Object filter = "";
private AppListFragment.Type filterType = AppListFragment.Type.NAME;
private final int HIDDEN_APP = 0; private final int HIDDEN_APP = 0;
private final int DISPLAYED_APP = 1; private final int DISPLAYED_APP = 1;
private final Comparator<ApplicationViewModel> alphaPackageComparator = (app1, app2) -> {
if (app1.label != null && app2.label != null)
return app1.label.toString().compareToIgnoreCase(app2.label.toString());
else if (app2.label != null)
return -1;
else if (app1.label != null)
return 1;
else
return 0;
};
private List<ApplicationViewModel> applicationViewModels;
private Object filter = "";
private AppListFragment.Type filterType = AppListFragment.Type.NAME;
private int displayedApp = 0; private int displayedApp = 0;
private Comparator<ApplicationViewModel> alphaPackageComparator = new Comparator<ApplicationViewModel>() { public ApplicationListAdapter(OnAppClickListener listener) {
@Override
public int compare(ApplicationViewModel app1, ApplicationViewModel app2) {
if(app1.label != null && app2.label != null)
return app1.label.toString().compareToIgnoreCase(app2.label.toString());
else if(app2.label != null)
return -1;
else if(app1.label != null)
return 1;
else
return 0;
}
};
public ApplicationListAdapter(Context context, OnAppClickListener listener) {
applicationViewModels = new ArrayList<>(); applicationViewModels = new ArrayList<>();
onAppClickListener = listener; onAppClickListener = listener;
} }
@Override @Override
public int getItemViewType(int position){ public int getItemViewType(int position) {
return applicationViewModels.get(position).isVisible ? DISPLAYED_APP : HIDDEN_APP; return applicationViewModels.get(position).isVisible ? DISPLAYED_APP : HIDDEN_APP;
} }
@NonNull @NonNull
@Override @Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if( viewType == HIDDEN_APP) if (viewType == HIDDEN_APP)
return new ApplicationEmptyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.app_item_empty, parent, false)); return new ApplicationEmptyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.app_item_empty, parent, false));
else else
return new ApplicationListViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.app_item, parent, false)); return new ApplicationListViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.app_item, parent, false));
@ -86,7 +82,7 @@ public class ApplicationListAdapter extends RecyclerView.Adapter {
@Override @Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
if( viewHolder.getItemViewType() == DISPLAYED_APP) { if (viewHolder.getItemViewType() == DISPLAYED_APP) {
final ApplicationListViewHolder holder = (ApplicationListViewHolder) viewHolder; final ApplicationListViewHolder holder = (ApplicationListViewHolder) viewHolder;
ApplicationViewModel vm = applicationViewModels.get(position); ApplicationViewModel vm = applicationViewModels.get(position);
holder.setViewModel(vm); holder.setViewModel(vm);
@ -97,7 +93,8 @@ public class ApplicationListAdapter extends RecyclerView.Adapter {
onAppClickListener.onAppClick(vm); onAppClickListener.onAppClick(vm);
} }
}); });
}else { } else //noinspection RedundantSuppression
{
//noinspection unused //noinspection unused
final ApplicationEmptyViewHolder holder = (ApplicationEmptyViewHolder) viewHolder; final ApplicationEmptyViewHolder holder = (ApplicationEmptyViewHolder) viewHolder;
//If something should be done for app that are hidden, it's here //If something should be done for app that are hidden, it's here
@ -112,14 +109,52 @@ public class ApplicationListAdapter extends RecyclerView.Adapter {
public void displayAppList(List<ApplicationViewModel> applications) { public void displayAppList(List<ApplicationViewModel> applications) {
applicationViewModels = applications; applicationViewModels = applications;
Collections.sort(applicationViewModels, alphaPackageComparator); Collections.sort(applicationViewModels, alphaPackageComparator);
filter(filterType,filter); filter(filterType, filter);
} }
public int getDisplayedApps() { public int getDisplayedApps() {
return displayedApp; return displayedApp;
} }
static class ApplicationEmptyViewHolder extends RecyclerView.ViewHolder{ public void filter(AppListFragment.Type type, Object filterObject) {
displayedApp = 0;
if (type.equals(AppListFragment.Type.NAME)) {
filter = filterObject;
filterType = type;
String filterStr = (String) filterObject;
Pattern p = Pattern.compile(Pattern.quote(filterStr.trim()), Pattern.CASE_INSENSITIVE);
for (ApplicationViewModel app : applicationViewModels) {
app.isVisible = p.matcher(app.label).find();
if (app.isVisible)
displayedApp++;
}
} else if (type.equals(AppListFragment.Type.TRACKER)) {
filter = filterObject;
filterType = type;
Long filterLng = (Long) filterObject;
for (ApplicationViewModel app : applicationViewModels) {
app.isVisible = false;
if (app.trackers != null) {
for (Tracker tracker : app.trackers) {
if (tracker.id == filterLng) {
app.isVisible = true;
displayedApp++;
break;
}
}
}
}
}
notifyDataSetChanged();
}
public interface OnAppClickListener {
void onAppClick(ApplicationViewModel vm);
}
static class ApplicationEmptyViewHolder extends RecyclerView.ViewHolder {
ApplicationEmptyViewHolder(View itemView) { ApplicationEmptyViewHolder(View itemView) {
super(itemView); super(itemView);
} }
@ -152,11 +187,11 @@ public class ApplicationListAdapter extends RecyclerView.Adapter {
appItemBinding.appLogo.setImageDrawable(viewModel.icon); appItemBinding.appLogo.setImageDrawable(viewModel.icon);
appItemBinding.appName.setText(viewModel.label); appItemBinding.appName.setText(viewModel.label);
appItemBinding.source.setText(context.getString(R.string.source,viewModel.source)); appItemBinding.source.setText(context.getString(R.string.source, viewModel.source));
long size = viewModel.requestedPermissions != null ? viewModel.requestedPermissions.length : 0; long size = viewModel.requestedPermissions != null ? viewModel.requestedPermissions.length : 0;
appItemBinding.appPermissionNb.setText(String.valueOf(size)); appItemBinding.appPermissionNb.setText(String.valueOf(size));
if(size == 0) if (size == 0)
appItemBinding.appPermissionNb.setBackgroundResource(R.drawable.square_green); appItemBinding.appPermissionNb.setBackgroundResource(R.drawable.square_green);
else if (size < 5) else if (size < 5)
appItemBinding.appPermissionNb.setBackgroundResource(R.drawable.square_light_yellow); appItemBinding.appPermissionNb.setBackgroundResource(R.drawable.square_light_yellow);
@ -164,24 +199,24 @@ public class ApplicationListAdapter extends RecyclerView.Adapter {
appItemBinding.appPermissionNb.setBackgroundResource(R.drawable.square_light_red); appItemBinding.appPermissionNb.setBackgroundResource(R.drawable.square_light_red);
Report report = viewModel.report; Report report = viewModel.report;
if(report != null) { if (report != null) {
Set<Tracker> trackers = viewModel.trackers; Set<Tracker> trackers = viewModel.trackers;
size = trackers.size(); size = trackers.size();
appItemBinding.appTrackerNb.setText(String.valueOf(size)); appItemBinding.appTrackerNb.setText(String.valueOf(size));
if(size == 0) if (size == 0)
appItemBinding.appTrackerNb.setBackgroundResource(R.drawable.square_green); appItemBinding.appTrackerNb.setBackgroundResource(R.drawable.square_green);
else if (size < 5) else if (size < 5)
appItemBinding.appTrackerNb.setBackgroundResource(R.drawable.square_light_yellow); appItemBinding.appTrackerNb.setBackgroundResource(R.drawable.square_light_yellow);
else else
appItemBinding.appTrackerNb.setBackgroundResource(R.drawable.square_light_red); appItemBinding.appTrackerNb.setBackgroundResource(R.drawable.square_light_red);
if(versionName != null && !report.version.equals(viewModel.versionName)) { if (versionName != null && !report.version.equals(viewModel.versionName)) {
String string = context.getString(R.string.tested,versionName, report.version); String string = context.getString(R.string.tested, versionName, report.version);
appItemBinding.otherVersion.setText(string); appItemBinding.otherVersion.setText(string);
appItemBinding.otherVersion.setVisibility(View.VISIBLE); appItemBinding.otherVersion.setVisibility(View.VISIBLE);
} else if (versionName == null && report.versionCode != versionCode) { } else if (versionName == null && report.versionCode != versionCode) {
String string = context.getString(R.string.tested,String.valueOf(versionCode),String.valueOf(report.versionCode)); String string = context.getString(R.string.tested, String.valueOf(versionCode), String.valueOf(report.versionCode));
appItemBinding.otherVersion.setText(string); appItemBinding.otherVersion.setText(string);
appItemBinding.otherVersion.setVisibility(View.VISIBLE); appItemBinding.otherVersion.setVisibility(View.VISIBLE);
} }
@ -192,42 +227,4 @@ public class ApplicationListAdapter extends RecyclerView.Adapter {
} }
} }
} }
public interface OnAppClickListener {
void onAppClick(ApplicationViewModel vm);
}
public void filter(AppListFragment.Type type, Object filterObject) {
displayedApp = 0;
if (type.equals(AppListFragment.Type.NAME)) {
filter = filterObject;
filterType = type;
String filterStr = (String) filterObject;
Pattern p = Pattern.compile(Pattern.quote(filterStr.trim()), Pattern.CASE_INSENSITIVE);
for (ApplicationViewModel app : applicationViewModels) {
app.isVisible = p.matcher(app.label).find();
if(app.isVisible)
displayedApp++;
}
} else if(type.equals(AppListFragment.Type.TRACKER)) {
filter = filterObject;
filterType = type;
Long filterLng = (Long) filterObject;
for (ApplicationViewModel app : applicationViewModels) {
app.isVisible = false;
if (app.trackers != null) {
for (Tracker tracker : app.trackers) {
if (tracker.id == filterLng) {
app.isVisible = true;
displayedApp++;
break;
}
}
}
}
}
notifyDataSetChanged();
}
} }

View File

@ -14,7 +14,7 @@ import org.eu.exodus_privacy.exodusprivacy.objects.Permission;
import java.util.List; import java.util.List;
public class PermissionListAdapter extends RecyclerView.Adapter<PermissionListAdapter.TrackerListViewHolder>{ public class PermissionListAdapter extends RecyclerView.Adapter<PermissionListAdapter.TrackerListViewHolder> {
private List<Permission> permissionList; private List<Permission> permissionList;
@ -25,13 +25,13 @@ public class PermissionListAdapter extends RecyclerView.Adapter<PermissionListAd
@NonNull @NonNull
@Override @Override
public PermissionListAdapter.TrackerListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public PermissionListAdapter.TrackerListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
PermissionItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),R.layout.permission_item,parent,false); PermissionItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.permission_item, parent, false);
return new TrackerListViewHolder(binding); return new TrackerListViewHolder(binding);
} }
@Override @Override
public void onBindViewHolder(@NonNull PermissionListAdapter.TrackerListViewHolder holder, int position) { public void onBindViewHolder(@NonNull PermissionListAdapter.TrackerListViewHolder holder, int position) {
if(permissionList == null || permissionList.size() == 0) if (permissionList == null || permissionList.size() == 0)
holder.setupData(null); holder.setupData(null);
else else
holder.setupData(permissionList.get(position)); holder.setupData(permissionList.get(position));
@ -39,7 +39,7 @@ public class PermissionListAdapter extends RecyclerView.Adapter<PermissionListAd
@Override @Override
public int getItemCount() { public int getItemCount() {
if(permissionList == null || permissionList.size() == 0) if (permissionList == null || permissionList.size() == 0)
return 0; return 0;
else else
return permissionList.size(); return permissionList.size();
@ -50,7 +50,7 @@ public class PermissionListAdapter extends RecyclerView.Adapter<PermissionListAd
} }
class TrackerListViewHolder extends RecyclerView.ViewHolder { static class TrackerListViewHolder extends RecyclerView.ViewHolder {
PermissionItemBinding permissionItemBinding; PermissionItemBinding permissionItemBinding;
@ -60,32 +60,30 @@ public class PermissionListAdapter extends RecyclerView.Adapter<PermissionListAd
} }
void setupData(Permission permission) { void setupData(Permission permission) {
if(permission != null) { if (permission != null) {
if(permission.name != null) { if (permission.name != null) {
permissionItemBinding.permissionShort.setText(permission.name); permissionItemBinding.permissionShort.setText(permission.name);
permissionItemBinding.permissionShort.setVisibility(View.VISIBLE); permissionItemBinding.permissionShort.setVisibility(View.VISIBLE);
} } else
else
permissionItemBinding.permissionShort.setVisibility(View.GONE); permissionItemBinding.permissionShort.setVisibility(View.GONE);
permissionItemBinding.permissionName.setText(permission.fullName.substring(permission.fullName.lastIndexOf(".")+1)); permissionItemBinding.permissionName.setText(permission.fullName.substring(permission.fullName.lastIndexOf(".") + 1));
permissionItemBinding.permissionDescription.setText(permission.description); permissionItemBinding.permissionDescription.setText(permission.description);
if(permission.icon != null) if (permission.icon != null)
permissionItemBinding.icon.setImageDrawable(permission.icon); permissionItemBinding.icon.setImageDrawable(permission.icon);
if(!permission.dangerous) if (!permission.dangerous)
permissionItemBinding.dangerous.setVisibility(View.GONE); permissionItemBinding.dangerous.setVisibility(View.GONE);
else else
permissionItemBinding.dangerous.setVisibility(View.VISIBLE); permissionItemBinding.dangerous.setVisibility(View.VISIBLE);
manageExpanded(permission); manageExpanded(permission);
permissionItemBinding.mainLayout.setOnClickListener((View.OnClickListener) v -> { permissionItemBinding.mainLayout.setOnClickListener(v -> {
if( permission.description != null && permission.description.trim().length() > 0) { if (permission.description != null && permission.description.trim().length() > 0) {
permission.expanded = !permission.expanded; permission.expanded = !permission.expanded;
manageExpanded(permission); manageExpanded(permission);
} }
}); });
} } else {
else {
permissionItemBinding.permissionName.setText(R.string.no_permissions); permissionItemBinding.permissionName.setText(R.string.no_permissions);
permissionItemBinding.arrow.setText(" "); permissionItemBinding.arrow.setText(" ");
permissionItemBinding.permissionShort.setVisibility(View.GONE); permissionItemBinding.permissionShort.setVisibility(View.GONE);
@ -96,11 +94,11 @@ public class PermissionListAdapter extends RecyclerView.Adapter<PermissionListAd
} }
void manageExpanded(Permission permission) { void manageExpanded(Permission permission) {
if(permission.expanded) { if (permission.expanded) {
permissionItemBinding.arrow.setText(""); permissionItemBinding.arrow.setText("");
permissionItemBinding.permissionDescription.setVisibility(View.VISIBLE); permissionItemBinding.permissionDescription.setVisibility(View.VISIBLE);
} else { } else {
if( permission.description != null && permission.description.trim().length() > 0 ) if (permission.description != null && permission.description.trim().length() > 0)
permissionItemBinding.arrow.setText(""); permissionItemBinding.arrow.setText("");
else else
permissionItemBinding.arrow.setText(""); permissionItemBinding.arrow.setText("");

View File

@ -1,7 +1,6 @@
package org.eu.exodus_privacy.exodusprivacy.adapters; package org.eu.exodus_privacy.exodusprivacy.adapters;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -20,11 +19,12 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
public class TrackerListAdapter extends RecyclerView.Adapter<TrackerListAdapter.TrackerListViewHolder>{ public class TrackerListAdapter extends RecyclerView.Adapter<TrackerListAdapter.TrackerListViewHolder> {
private final OnTrackerClickListener trackerClickListener;
private final int layout;
private final Comparator<Tracker> alphaTrackerComparator = (track1, track2) -> track1.name.compareToIgnoreCase(track2.name);
private List<Tracker> trackersList; private List<Tracker> trackersList;
private OnTrackerClickListener trackerClickListener;
private int layout;
public TrackerListAdapter(Set<Tracker> trackerList, int resource, OnTrackerClickListener listener) { public TrackerListAdapter(Set<Tracker> trackerList, int resource, OnTrackerClickListener listener) {
setTrackers(trackerList); setTrackers(trackerList);
@ -35,13 +35,13 @@ public class TrackerListAdapter extends RecyclerView.Adapter<TrackerListAdapter.
@NonNull @NonNull
@Override @Override
public TrackerListAdapter.TrackerListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { public TrackerListAdapter.TrackerListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),layout,parent,false); ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), layout, parent, false);
return new TrackerListViewHolder(binding); return new TrackerListViewHolder(binding);
} }
@Override @Override
public void onBindViewHolder(@NonNull TrackerListAdapter.TrackerListViewHolder holder, int position) { public void onBindViewHolder(@NonNull TrackerListAdapter.TrackerListViewHolder holder, int position) {
if(trackersList == null || trackersList.size() == 0) if (trackersList == null || trackersList.size() == 0)
holder.setupData(null); holder.setupData(null);
else else
holder.setupData(trackersList.get(position)); holder.setupData(trackersList.get(position));
@ -49,21 +49,23 @@ public class TrackerListAdapter extends RecyclerView.Adapter<TrackerListAdapter.
@Override @Override
public int getItemCount() { public int getItemCount() {
if(trackersList == null || trackersList.size() == 0) if (trackersList == null || trackersList.size() == 0)
return 1; return 1;
else else
return trackersList.size(); return trackersList.size();
} }
private Comparator<Tracker> alphaTrackerComparator = (track1, track2) -> track1.name.compareToIgnoreCase(track2.name);
public void setTrackers(Set<Tracker> trackers) { public void setTrackers(Set<Tracker> trackers) {
if(trackers != null) { if (trackers != null) {
trackersList = new ArrayList<>(trackers); trackersList = new ArrayList<>(trackers);
Collections.sort(trackersList, alphaTrackerComparator); Collections.sort(trackersList, alphaTrackerComparator);
} }
} }
public interface OnTrackerClickListener {
void onTrackerClick(long trackerId);
}
class TrackerListViewHolder extends RecyclerView.ViewHolder { class TrackerListViewHolder extends RecyclerView.ViewHolder {
ViewDataBinding viewDataBinding; ViewDataBinding viewDataBinding;
@ -74,23 +76,16 @@ public class TrackerListAdapter extends RecyclerView.Adapter<TrackerListAdapter.
} }
void setupData(Tracker tracker) { void setupData(Tracker tracker) {
if(viewDataBinding instanceof TrackerItemBinding) { if (viewDataBinding instanceof TrackerItemBinding) {
TrackerItemBinding binding = (TrackerItemBinding) viewDataBinding; TrackerItemBinding binding = (TrackerItemBinding) viewDataBinding;
if(tracker != null) { if (tracker != null) {
binding.trackerName.setText(tracker.name + ""); binding.trackerName.setText(String.format("%s ➤", tracker.name));
binding.getRoot().setOnClickListener(v -> { binding.getRoot().setOnClickListener(v -> trackerClickListener.onTrackerClick(tracker.id));
trackerClickListener.onTrackerClick(tracker.id); } else
});
}
else
binding.trackerName.setText(R.string.no_trackers); binding.trackerName.setText(R.string.no_trackers);
} }
} }
} }
public interface OnTrackerClickListener{
public void onTrackerClick(long trackerId);
}
} }

View File

@ -32,7 +32,7 @@ public class AppListFragment extends Fragment {
@Override @Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//create binding //create binding
applistBinding = DataBindingUtil.inflate(inflater, R.layout.applist,container,false); applistBinding = DataBindingUtil.inflate(inflater, R.layout.applist, container, false);
//init variables //init variables
if (applications == null) if (applications == null)
applications = new ArrayList<>(); applications = new ArrayList<>();
@ -40,28 +40,28 @@ public class AppListFragment extends Fragment {
//configure list //configure list
applistBinding.appList.setLayoutManager(new LinearLayoutManager(context)); applistBinding.appList.setLayoutManager(new LinearLayoutManager(context));
applistBinding.appList.setVerticalScrollBarEnabled(scrollbarEnabled); applistBinding.appList.setVerticalScrollBarEnabled(scrollbarEnabled);
adapter = new ApplicationListAdapter(context, onAppClickListener); adapter = new ApplicationListAdapter(onAppClickListener);
adapter.displayAppList(applications); adapter.displayAppList(applications);
adapter.filter(filterType,filterObject); adapter.filter(filterType, filterObject);
applistBinding.appList.setAdapter(adapter); applistBinding.appList.setAdapter(adapter);
return applistBinding.getRoot(); return applistBinding.getRoot();
} }
public void setOnAppClickListener(ApplicationListAdapter.OnAppClickListener listener){ public void setOnAppClickListener(ApplicationListAdapter.OnAppClickListener listener) {
onAppClickListener = listener; onAppClickListener = listener;
} }
public void setApplications(List<ApplicationViewModel> applicationList){ public void setApplications(List<ApplicationViewModel> applicationList) {
applications = applicationList; applications = applicationList;
if(adapter != null) if (adapter != null)
adapter.displayAppList(applications); adapter.displayAppList(applications);
} }
public void setFilter(Type type, Object filter){ public void setFilter(Type type, Object filter) {
filterType = type; filterType = type;
filterObject = filter; filterObject = filter;
if(adapter != null) if (adapter != null)
adapter.filter(type,filterObject); adapter.filter(type, filterObject);
} }
public void disableScrollBar() { public void disableScrollBar() {

View File

@ -16,16 +16,11 @@ import java.util.Map;
class ComputeAppListTask extends AsyncTask<Void, Void, List<ApplicationViewModel>> { class ComputeAppListTask extends AsyncTask<Void, Void, List<ApplicationViewModel>> {
interface Listener {
void onAppsComputed(List<ApplicationViewModel> apps);
}
private static final String gStore = "com.android.vending"; private static final String gStore = "com.android.vending";
private static final String fdroid = "ord.fdroid.fdroid"; private static final String fdroid = "ord.fdroid.fdroid";
private final WeakReference<PackageManager> packageManagerRef;
private WeakReference<PackageManager> packageManagerRef; private final WeakReference<DatabaseManager> databaseManagerRef;
private WeakReference<DatabaseManager> databaseManagerRef; private final WeakReference<Listener> listenerRef;
private WeakReference<Listener> listenerRef;
ComputeAppListTask(WeakReference<PackageManager> packageManagerRef, ComputeAppListTask(WeakReference<PackageManager> packageManagerRef,
WeakReference<DatabaseManager> databaseManagerRef, WeakReference<DatabaseManager> databaseManagerRef,
@ -40,7 +35,7 @@ class ComputeAppListTask extends AsyncTask<Void, Void, List<ApplicationViewModel
DatabaseManager databaseManager = databaseManagerRef.get(); DatabaseManager databaseManager = databaseManagerRef.get();
List<ApplicationViewModel> vms = new ArrayList<>(); List<ApplicationViewModel> vms = new ArrayList<>();
if(packageManager != null && databaseManager != null) { if (packageManager != null && databaseManager != null) {
List<PackageInfo> installedPackages = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS); List<PackageInfo> installedPackages = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS);
vms = applyStoreFilter(installedPackages, databaseManager, packageManager); vms = applyStoreFilter(installedPackages, databaseManager, packageManager);
convertPackagesToViewModels(vms, databaseManager, packageManager); convertPackagesToViewModels(vms, databaseManager, packageManager);
@ -52,14 +47,14 @@ class ComputeAppListTask extends AsyncTask<Void, Void, List<ApplicationViewModel
protected void onPostExecute(List<ApplicationViewModel> vms) { protected void onPostExecute(List<ApplicationViewModel> vms) {
Listener listener = listenerRef.get(); Listener listener = listenerRef.get();
if(listener != null) { if (listener != null) {
listener.onAppsComputed(vms); listener.onAppsComputed(vms);
} }
} }
private void convertPackagesToViewModels(List<ApplicationViewModel> appsToBuild, private void convertPackagesToViewModels(List<ApplicationViewModel> appsToBuild,
DatabaseManager databaseManager, DatabaseManager databaseManager,
PackageManager packageManager) { PackageManager packageManager) {
for (ApplicationViewModel vm : appsToBuild) { for (ApplicationViewModel vm : appsToBuild) {
try { try {
PackageInfo pi = packageManager.getPackageInfo(vm.packageName, PackageManager.GET_PERMISSIONS); PackageInfo pi = packageManager.getPackageInfo(vm.packageName, PackageManager.GET_PERMISSIONS);
@ -71,8 +66,8 @@ class ComputeAppListTask extends AsyncTask<Void, Void, List<ApplicationViewModel
} }
private void buildViewModelFromPackageInfo(ApplicationViewModel vm, PackageInfo pi, private void buildViewModelFromPackageInfo(ApplicationViewModel vm, PackageInfo pi,
DatabaseManager databaseManager, DatabaseManager databaseManager,
PackageManager packageManager) { PackageManager packageManager) {
vm.versionName = pi.versionName; vm.versionName = pi.versionName;
vm.packageName = pi.packageName; vm.packageName = pi.packageName;
@ -101,8 +96,8 @@ class ComputeAppListTask extends AsyncTask<Void, Void, List<ApplicationViewModel
} }
private List<ApplicationViewModel> applyStoreFilter(List<PackageInfo> packageInfos, private List<ApplicationViewModel> applyStoreFilter(List<PackageInfo> packageInfos,
DatabaseManager databaseManager, DatabaseManager databaseManager,
PackageManager packageManager) { PackageManager packageManager) {
List<ApplicationViewModel> result = new ArrayList<>(); List<ApplicationViewModel> result = new ArrayList<>();
for (PackageInfo packageInfo : packageInfos) { for (PackageInfo packageInfo : packageInfos) {
String packageName = packageInfo.packageName; String packageName = packageInfo.packageName;
@ -111,28 +106,32 @@ class ComputeAppListTask extends AsyncTask<Void, Void, List<ApplicationViewModel
vm.packageName = packageName; vm.packageName = packageName;
if (!gStore.equals(installerPackageName) && !fdroid.equals(installerPackageName)) { if (!gStore.equals(installerPackageName) && !fdroid.equals(installerPackageName)) {
String auid = Utils.getCertificateSHA1Fingerprint(packageManager, packageName); String auid = Utils.getCertificateSHA1Fingerprint(packageManager, packageName);
Map<String,String> sources = databaseManager.getSources(packageName); Map<String, String> sources = databaseManager.getSources(packageName);
for(Map.Entry<String,String> entry : sources.entrySet()) { for (Map.Entry<String, String> entry : sources.entrySet()) {
if(entry.getValue().equalsIgnoreCase(auid)) { if (entry.getValue().equalsIgnoreCase(auid)) {
vm.source = entry.getKey(); vm.source = entry.getKey();
break; break;
} }
} }
} else if (gStore.equals(installerPackageName)) { } else if (gStore.equals(installerPackageName)) {
vm.source = "google"; vm.source = "google";
} else { } else {
vm.source = "fdroid"; vm.source = "fdroid";
} }
ApplicationInfo appInfo = null; ApplicationInfo appInfo = null;
try { try {
appInfo = packageManager.getApplicationInfo(packageName,0); appInfo = packageManager.getApplicationInfo(packageName, 0);
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
} }
if(vm.source != null && appInfo != null && appInfo.enabled) if (vm.source != null && appInfo != null && appInfo.enabled)
result.add(vm); result.add(vm);
} }
return result; return result;
} }
interface Listener {
void onAppsComputed(List<ApplicationViewModel> apps);
}
} }

View File

@ -41,35 +41,35 @@ public class HomeFragment extends Fragment implements ComputeAppListTask.Listene
private boolean startRefreshAsked; private boolean startRefreshAsked;
private boolean refreshInProgress; private boolean refreshInProgress;
private int lastResource=0; private int lastResource = 0;
private int lastProgress=0; private int lastProgress = 0;
private int lastMaxProgress=0; private int lastMaxProgress = 0;
@Override @Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(applications == null) if (applications == null)
applications = new ArrayList<>(); applications = new ArrayList<>();
homeBinding = DataBindingUtil.inflate(inflater, R.layout.home,container,false); homeBinding = DataBindingUtil.inflate(inflater, R.layout.home, container, false);
appListFragment = new AppListFragment(); appListFragment = new AppListFragment();
appListFragment.setOnAppClickListener(onAppClickListener); appListFragment.setOnAppClickListener(onAppClickListener);
FragmentManager fragmentManager = getChildFragmentManager(); FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction(); FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.app_list_container,appListFragment); transaction.replace(R.id.app_list_container, appListFragment);
transaction.commit(); transaction.commit();
Context context = homeBinding.getRoot().getContext(); Context context = homeBinding.getRoot().getContext();
packageManager = context.getPackageManager(); packageManager = context.getPackageManager();
homeBinding.swipeRefresh.setOnRefreshListener(this::startRefresh); homeBinding.swipeRefresh.setOnRefreshListener(this::startRefresh);
if(packageManager != null) { if (packageManager != null) {
homeBinding.noPackageManager.setVisibility(View.GONE); homeBinding.noPackageManager.setVisibility(View.GONE);
onAppsComputed(applications); onAppsComputed(applications);
if(applications.isEmpty()) if (applications.isEmpty())
displayAppListAsync(); displayAppListAsync();
if(startRefreshAsked) if (startRefreshAsked)
startRefresh(); startRefresh();
else if (refreshInProgress) { else if (refreshInProgress) {
homeBinding.layoutProgress.setVisibility(View.VISIBLE); homeBinding.layoutProgress.setVisibility(View.VISIBLE);
homeBinding.swipeRefresh.setRefreshing(true); homeBinding.swipeRefresh.setRefreshing(true);
updateProgress(lastResource,lastProgress,lastMaxProgress); updateProgress(lastResource, lastProgress, lastMaxProgress);
} }
} else { } else {
homeBinding.noPackageManager.setVisibility(View.VISIBLE); homeBinding.noPackageManager.setVisibility(View.VISIBLE);
@ -77,8 +77,8 @@ public class HomeFragment extends Fragment implements ComputeAppListTask.Listene
return homeBinding.getRoot(); return homeBinding.getRoot();
} }
public void startRefresh(){ public void startRefresh() {
if(packageManager != null) { if (packageManager != null) {
refreshInProgress = true; refreshInProgress = true;
homeBinding.layoutProgress.setVisibility(View.VISIBLE); homeBinding.layoutProgress.setVisibility(View.VISIBLE);
homeBinding.swipeRefresh.setRefreshing(true); homeBinding.swipeRefresh.setRefreshing(true);
@ -124,16 +124,16 @@ public class HomeFragment extends Fragment implements ComputeAppListTask.Listene
lastResource = resourceId; lastResource = resourceId;
lastProgress = progress; lastProgress = progress;
lastMaxProgress = maxProgress; lastMaxProgress = maxProgress;
if(lastResource == 0) if (lastResource == 0)
return; return;
Activity activity = getActivity(); Activity activity = getActivity();
if(activity == null) if (activity == null)
return; return;
activity.runOnUiThread(() -> { activity.runOnUiThread(() -> {
if (homeBinding == null) if (homeBinding == null)
return; return;
if(maxProgress > 0) if (maxProgress > 0)
homeBinding.statusProgress.setText(activity.getString(resourceId)+" "+progress+"/"+maxProgress);//fixme homeBinding.statusProgress.setText(activity.getString(resourceId) + " " + progress + "/" + maxProgress);//fixme
else else
homeBinding.statusProgress.setText(activity.getString(resourceId)); homeBinding.statusProgress.setText(activity.getString(resourceId));
homeBinding.progress.setMax(maxProgress); homeBinding.progress.setMax(maxProgress);
@ -144,12 +144,12 @@ public class HomeFragment extends Fragment implements ComputeAppListTask.Listene
public void setOnAppClickListener(ApplicationListAdapter.OnAppClickListener onAppClickListener) { public void setOnAppClickListener(ApplicationListAdapter.OnAppClickListener onAppClickListener) {
this.onAppClickListener = onAppClickListener; this.onAppClickListener = onAppClickListener;
if(appListFragment != null) if (appListFragment != null)
appListFragment.setOnAppClickListener(onAppClickListener); appListFragment.setOnAppClickListener(onAppClickListener);
} }
public void filter(String filter){ public void filter(String filter) {
appListFragment.setFilter(AppListFragment.Type.NAME,filter); appListFragment.setFilter(AppListFragment.Type.NAME, filter);
} }
private void displayAppListAsync() { private void displayAppListAsync() {
@ -173,8 +173,8 @@ public class HomeFragment extends Fragment implements ComputeAppListTask.Listene
homeBinding.logo.setVisibility(View.GONE); homeBinding.logo.setVisibility(View.GONE);
homeBinding.noAppFound.setVisibility(apps.isEmpty() ? View.VISIBLE : View.GONE); homeBinding.noAppFound.setVisibility(apps.isEmpty() ? View.VISIBLE : View.GONE);
appListFragment.setApplications(apps); appListFragment.setApplications(apps);
if(!apps.isEmpty()) { if (!apps.isEmpty()) {
if(startupRefresh) { if (startupRefresh) {
startRefresh(); startRefresh();
startupRefresh = false; startupRefresh = false;
} }

View File

@ -44,7 +44,8 @@ import org.eu.exodus_privacy.exodusprivacy.adapters.PermissionListAdapter;
import org.eu.exodus_privacy.exodusprivacy.adapters.TrackerListAdapter; import org.eu.exodus_privacy.exodusprivacy.adapters.TrackerListAdapter;
import org.eu.exodus_privacy.exodusprivacy.databinding.ReportBinding; import org.eu.exodus_privacy.exodusprivacy.databinding.ReportBinding;
import org.eu.exodus_privacy.exodusprivacy.objects.ReportDisplay; import org.eu.exodus_privacy.exodusprivacy.objects.ReportDisplay;
public class ReportFragment extends Fragment implements Updatable {
public class ReportFragment extends Fragment implements Updatable {
private PackageManager packageManager; private PackageManager packageManager;
private PackageInfo packageInfo = null; private PackageInfo packageInfo = null;
@ -52,7 +53,7 @@ public class ReportFragment extends Fragment implements Updatable {
private TrackerListAdapter.OnTrackerClickListener trackerClickListener; private TrackerListAdapter.OnTrackerClickListener trackerClickListener;
private ApplicationViewModel model; private ApplicationViewModel model;
public static ReportFragment newInstance(PackageManager packageManager,ApplicationViewModel model, PackageInfo packageInfo, TrackerListAdapter.OnTrackerClickListener trackerClickListener) { public static ReportFragment newInstance(PackageManager packageManager, ApplicationViewModel model, PackageInfo packageInfo, TrackerListAdapter.OnTrackerClickListener trackerClickListener) {
ReportFragment fragment = new ReportFragment(); ReportFragment fragment = new ReportFragment();
fragment.setPackageManager(packageManager); fragment.setPackageManager(packageManager);
fragment.setPackageInfo(packageInfo); fragment.setPackageInfo(packageInfo);
@ -68,7 +69,7 @@ public class ReportFragment extends Fragment implements Updatable {
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if(savedInstanceState != null && packageInfo == null) { if (savedInstanceState != null && packageInfo == null) {
packageInfo = savedInstanceState.getParcelable("PackageInfo"); packageInfo = savedInstanceState.getParcelable("PackageInfo");
} }
setHasOptionsMenu(true); setHasOptionsMenu(true);
@ -81,22 +82,22 @@ public class ReportFragment extends Fragment implements Updatable {
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
reportBinding = DataBindingUtil.inflate(inflater,R.layout.report,container,false); reportBinding = DataBindingUtil.inflate(inflater, R.layout.report, container, false);
onUpdateComplete(); onUpdateComplete();
return reportBinding.getRoot(); return reportBinding.getRoot();
} }
@Override @Override
public void onUpdateComplete() { public void onUpdateComplete() {
if(model != null) if (model != null)
onUpdateComplete(model); onUpdateComplete(model);
} }
public void onUpdateComplete(ApplicationViewModel model) { public void onUpdateComplete(ApplicationViewModel model) {
Context context = reportBinding.getRoot().getContext(); Context context = reportBinding.getRoot().getContext();
ReportDisplay reportDisplay = ReportDisplay.buildReportDisplay(context,model,packageManager,packageInfo); ReportDisplay reportDisplay = ReportDisplay.buildReportDisplay(context, model, packageManager, packageInfo);
ReportViewModel viewModel = new ReportViewModel(); ReportViewModel viewModel = new ReportViewModel();
viewModel.setReportDisplay(reportDisplay); viewModel.setReportDisplay(reportDisplay);
reportBinding.setReportInfo(viewModel); reportBinding.setReportInfo(viewModel);
@ -110,7 +111,7 @@ public class ReportFragment extends Fragment implements Updatable {
//setup trackers lists //setup trackers lists
reportBinding.trackers.setLayoutManager(new LinearLayoutManager(context)); reportBinding.trackers.setLayoutManager(new LinearLayoutManager(context));
TrackerListAdapter trackerAdapter = new TrackerListAdapter(reportDisplay.trackers,R.layout.tracker_item, trackerClickListener); TrackerListAdapter trackerAdapter = new TrackerListAdapter(reportDisplay.trackers, R.layout.tracker_item, trackerClickListener);
reportBinding.trackers.setNestedScrollingEnabled(false); reportBinding.trackers.setNestedScrollingEnabled(false);
reportBinding.trackers.setAdapter(trackerAdapter); reportBinding.trackers.setAdapter(trackerAdapter);
@ -133,14 +134,14 @@ public class ReportFragment extends Fragment implements Updatable {
reportBinding.viewStore.setOnClickListener(v -> { reportBinding.viewStore.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
if(reportDisplay.source.contains("google")) if (reportDisplay.source.contains("google"))
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id="+reportDisplay.packageName)); intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + reportDisplay.packageName));
else else
intent.setData(Uri.parse("https://f-droid.org/packages/"+reportDisplay.packageName)); intent.setData(Uri.parse("https://f-droid.org/packages/" + reportDisplay.packageName));
startActivity(intent); startActivity(intent);
}); });
if(reportDisplay.report != null) { if (reportDisplay.report != null) {
reportBinding.reportUrl.setOnClickListener(v -> { reportBinding.reportUrl.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://reports.exodus-privacy.eu.org/reports/" + reportDisplay.report.id + "/")); intent.setData(Uri.parse("https://reports.exodus-privacy.eu.org/reports/" + reportDisplay.report.id + "/"));

View File

@ -13,6 +13,7 @@ import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil; import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
@ -75,17 +76,17 @@ public class TrackerFragment extends Fragment implements ComputeAppListTask.List
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
trackerBinding = DataBindingUtil.inflate(inflater, R.layout.tracker,container,false); trackerBinding = DataBindingUtil.inflate(inflater, R.layout.tracker, container, false);
if (applications == null) if (applications == null)
applications = new ArrayList<>(); applications = new ArrayList<>();
appListFragment = new AppListFragment(); appListFragment = new AppListFragment();
appListFragment.setFilter(AppListFragment.Type.TRACKER,trackerId); appListFragment.setFilter(AppListFragment.Type.TRACKER, trackerId);
appListFragment.disableScrollBar(); appListFragment.disableScrollBar();
appListFragment.setOnAppClickListener(onAppClickListener); appListFragment.setOnAppClickListener(onAppClickListener);
FragmentManager manager = getChildFragmentManager(); FragmentManager manager = getChildFragmentManager();
FragmentTransaction transaction = manager.beginTransaction(); FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.applications,appListFragment); transaction.replace(R.id.applications, appListFragment);
transaction.commit(); transaction.commit();
Context context = trackerBinding.getRoot().getContext(); Context context = trackerBinding.getRoot().getContext();
packageManager = context.getPackageManager(); packageManager = context.getPackageManager();
@ -132,19 +133,19 @@ public class TrackerFragment extends Fragment implements ComputeAppListTask.List
appListFragment.setApplications(apps); appListFragment.setApplications(apps);
int total = appListFragment.getTotalApps(); int total = appListFragment.getTotalApps();
int displayedApps = appListFragment.getDisplayedApps(); int displayedApps = appListFragment.getDisplayedApps();
int percent = displayedApps*100/total; int percent = displayedApps * 100 / total;
if(percent >=50) if (percent >= 50)
trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_red); trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_red);
else if(percent >=33) else if (percent >= 33)
trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_dark_orange); trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_dark_orange);
else if(percent >=20) else if (percent >= 20)
trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_yellow); trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_yellow);
else else
trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_light_blue); trackerBinding.trackerPresenceNb.setBackgroundResource(R.drawable.square_light_blue);
trackerBinding.trackerPresenceNb.setText(percent+"%"); trackerBinding.trackerPresenceNb.setText(String.format("%s%%", percent));
Context context = trackerBinding.getRoot().getContext(); Context context = trackerBinding.getRoot().getContext();
String presence = context.getResources().getString(R.string.tracker_presence,displayedApps); String presence = context.getResources().getString(R.string.tracker_presence, displayedApps);
trackerBinding.trackerPresence.setText(presence); trackerBinding.trackerPresence.setText(presence);
trackerBinding.trackerPresenceTitle.setText(R.string.tracker_presence_in); trackerBinding.trackerPresenceTitle.setText(R.string.tracker_presence_in);
} }

View File

@ -23,8 +23,10 @@ import java.util.EventListener;
/* /*
Listener working with the NetworkManager to handle events Listener working with the NetworkManager to handle events
*/ */
public interface NetworkListener extends EventListener{ public interface NetworkListener extends EventListener {
void onSuccess(); void onSuccess();
void onError(String error); void onError(String error);
void onProgress(int resourceId, int progress, int maxProgress); void onProgress(int resourceId, int progress, int maxProgress);
} }

View File

@ -45,8 +45,8 @@ public class DatabaseManager extends SQLiteOpenHelper {
public static DatabaseManager getInstance(Context context) { public static DatabaseManager getInstance(Context context) {
if(instance == null) if (instance == null)
instance = new DatabaseManager(context,"Exodus.db",null,3); instance = new DatabaseManager(context, "Exodus.db", null, 3);
return instance; return instance;
} }
@ -61,7 +61,7 @@ public class DatabaseManager extends SQLiteOpenHelper {
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion <= 1) { if (oldVersion <= 1) {
db.execSQL("Alter Table applications add column auid TEXT"); db.execSQL("Alter Table applications add column auid TEXT");
} }
if (oldVersion <= 2) { if (oldVersion <= 2) {
@ -71,15 +71,15 @@ public class DatabaseManager extends SQLiteOpenHelper {
db.execSQL("Alter Table applications rename to old_apps"); db.execSQL("Alter Table applications rename to old_apps");
db.execSQL("Create Table if not exists applications (id INTEGER primary key autoincrement, package TEXT, name TEXT, creator TEXT, sources TEXT);"); db.execSQL("Create Table if not exists applications (id INTEGER primary key autoincrement, package TEXT, name TEXT, creator TEXT, sources TEXT);");
Cursor cursor = db.query("old_apps",null,null,null,null,null,null); Cursor cursor = db.query("old_apps", null, null, null, null, null, null);
while (cursor.moveToNext()){ while (cursor.moveToNext()) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put("package",cursor.getString(1)); values.put("package", cursor.getString(1));
values.put("name",cursor.getString(2)); values.put("name", cursor.getString(2));
values.put("creator",cursor.getString(3)); values.put("creator", cursor.getString(3));
String sources = "unknown:"+cursor.getString(4)+"|"; String sources = "unknown:" + cursor.getString(4) + "|";
values.put("sources",sources); values.put("sources", sources);
db.insert("applications",null,values); db.insert("applications", null, values);
} }
cursor.close(); cursor.close();
db.execSQL("Drop Table old_apps"); db.execSQL("Drop Table old_apps");
@ -94,53 +94,52 @@ public class DatabaseManager extends SQLiteOpenHelper {
} }
private boolean existReport(SQLiteDatabase db, long reportId) { private boolean existReport(SQLiteDatabase db, long reportId) {
return exist(db,"reports",reportId); return exist(db, "reports", reportId);
} }
private boolean existApplication(SQLiteDatabase db, String packageName) { private boolean existApplication(SQLiteDatabase db, String packageName) {
String[] columns = {"package"}; String[] columns = {"package"};
String where = "package = ?"; String where = "package = ?";
String[] whereArgs = {packageName}; String[] whereArgs = {packageName};
Cursor cursor = db.query("applications",columns,where,whereArgs,null,null,null); Cursor cursor = db.query("applications", columns, where, whereArgs, null, null, null);
boolean exist = cursor.getCount() != 0; boolean exist = cursor.getCount() != 0;
cursor.close(); cursor.close();
return exist; return exist;
} }
private boolean existTracker(SQLiteDatabase db, long trackerId) { private boolean existTracker(SQLiteDatabase db, long trackerId) {
return exist(db,"trackers",trackerId); return exist(db, "trackers", trackerId);
} }
private boolean exist(SQLiteDatabase db, String table, long id) { private boolean exist(SQLiteDatabase db, String table, long id) {
if(id == -1) if (id == -1)
return false; return false;
String[] columns = {"id"}; String[] columns = {"id"};
String where = "id = ?"; String where = "id = ?";
String[] whereArgs = {String.valueOf(id)}; String[] whereArgs = {String.valueOf(id)};
Cursor cursor = db.query(table,columns,where,whereArgs,null,null,null); Cursor cursor = db.query(table, columns, where, whereArgs, null, null, null);
boolean exist = cursor.getCount() != 0; boolean exist = cursor.getCount() != 0;
cursor.close(); cursor.close();
return exist; return exist;
} }
private void insertOrUpdateTracker(SQLiteDatabase db,Tracker tracker) { private void insertOrUpdateTracker(SQLiteDatabase db, Tracker tracker) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put("name",tracker.name); values.put("name", tracker.name);
values.put("code_signature",tracker.codeSignature); values.put("code_signature", tracker.codeSignature);
values.put("network_signature",tracker.networkSignature); values.put("network_signature", tracker.networkSignature);
values.put("website",tracker.website); values.put("website", tracker.website);
values.put("description",tracker.description); values.put("description", tracker.description);
values.put("creation_date",tracker.creationDate.getTimeInMillis()); values.put("creation_date", tracker.creationDate.getTimeInMillis());
if(!existTracker(db,tracker.id)) { if (!existTracker(db, tracker.id)) {
values.put("id",tracker.id); values.put("id", tracker.id);
db.insert("trackers", null, values); db.insert("trackers", null, values);
} } else {
else {
String where = "id = ?"; String where = "id = ?";
String[] whereArgs = {String.valueOf(tracker.id)}; String[] whereArgs = {String.valueOf(tracker.id)};
db.update("trackers",values,where,whereArgs); db.update("trackers", values, where, whereArgs);
} }
} }
@ -148,54 +147,53 @@ public class DatabaseManager extends SQLiteOpenHelper {
SQLiteDatabase db = getWritableDatabase(); SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put("package", application.packageName); values.put("package", application.packageName);
values.put("name",application.name); values.put("name", application.name);
values.put("creator",application.creator); values.put("creator", application.creator);
values.put("sources",buildSourcesStr(application.sources)); values.put("sources", buildSourcesStr(application.sources));
if(!existApplication(db, application.packageName)) { if (!existApplication(db, application.packageName)) {
db.insert("applications", null, values); db.insert("applications", null, values);
} else { } else {
String where = "package = ?"; String where = "package = ?";
String[] whereArgs = {application.packageName}; String[] whereArgs = {application.packageName};
db.update("applications",values,where,whereArgs); db.update("applications", values, where, whereArgs);
} }
String[] columns = {"id"}; String[] columns = {"id"};
String where = "package = ?"; String where = "package = ?";
String[] whereArgs = {application.packageName}; String[] whereArgs = {application.packageName};
Cursor cursor = db.query("applications",columns,where,whereArgs,null,null,null); Cursor cursor = db.query("applications", columns, where, whereArgs, null, null, null);
if(cursor.moveToFirst()) { if (cursor.moveToFirst()) {
application.id = cursor.getLong(0); application.id = cursor.getLong(0);
} }
cursor.close(); cursor.close();
for(Report report : application.reports) { for (Report report : application.reports) {
insertOrUpdateReport(db,report,application.id); insertOrUpdateReport(db, report, application.id);
} }
} }
private void insertOrUpdateReport(SQLiteDatabase db, Report report, long appId) { private void insertOrUpdateReport(SQLiteDatabase db, Report report, long appId) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put("creation",report.creationDate.getTimeInMillis()); values.put("creation", report.creationDate.getTimeInMillis());
values.put("updateat",report.updateDate.getTimeInMillis()); values.put("updateat", report.updateDate.getTimeInMillis());
values.put("downloads",report.downloads); values.put("downloads", report.downloads);
values.put("version",report.version); values.put("version", report.version);
values.put("version_code",report.versionCode); values.put("version_code", report.versionCode);
values.put("app_id",appId); values.put("app_id", appId);
values.put("source",report.source); values.put("source", report.source);
if(!existReport(db,report.id)) { if (!existReport(db, report.id)) {
values.put("id",report.id); values.put("id", report.id);
db.insert("reports", null, values); db.insert("reports", null, values);
} } else {
else {
String where = "id = ?"; String where = "id = ?";
String[] whereArgs = {String.valueOf(report.id)}; String[] whereArgs = {String.valueOf(report.id)};
db.update("reports",values,where,whereArgs); db.update("reports", values, where, whereArgs);
} }
removeTrackers(report.id); removeTrackers(report.id);
for(Long tracker : report.trackers) { for (Long tracker : report.trackers) {
insertTrackerReport(db, tracker, report.id); insertTrackerReport(db, tracker, report.id);
} }
} }
@ -203,14 +201,14 @@ public class DatabaseManager extends SQLiteOpenHelper {
private void removeTrackers(long reportId) { private void removeTrackers(long reportId) {
String where = "report_id = ?"; String where = "report_id = ?";
String[] whereArgs = {String.valueOf(reportId)}; String[] whereArgs = {String.valueOf(reportId)};
getWritableDatabase().delete("trackers_reports",where,whereArgs); getWritableDatabase().delete("trackers_reports", where, whereArgs);
} }
private void insertTrackerReport(SQLiteDatabase db, long trackerId, long reportId) { private void insertTrackerReport(SQLiteDatabase db, long trackerId, long reportId) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put("report_id",reportId); values.put("report_id", reportId);
values.put("tracker_id",trackerId); values.put("tracker_id", trackerId);
db.insert("trackers_reports",null,values); db.insert("trackers_reports", null, values);
} }
public Report getReportFor(String packageName, String version, String source) { public Report getReportFor(String packageName, String version, String source) {
@ -218,8 +216,8 @@ public class DatabaseManager extends SQLiteOpenHelper {
String[] columns = {"id"}; String[] columns = {"id"};
String where = "package = ?"; String where = "package = ?";
String[] whereArgs = {packageName}; String[] whereArgs = {packageName};
Cursor cursor = db.query("applications",columns,where,whereArgs,null,null,null); Cursor cursor = db.query("applications", columns, where, whereArgs, null, null, null);
if(cursor.moveToFirst()) { if (cursor.moveToFirst()) {
long appId = cursor.getLong(0); long appId = cursor.getLong(0);
cursor.close(); cursor.close();
where = "app_id = ? and version = ? and source = ?"; where = "app_id = ? and version = ? and source = ?";
@ -228,9 +226,9 @@ public class DatabaseManager extends SQLiteOpenHelper {
whereArgs[1] = version; whereArgs[1] = version;
whereArgs[2] = source; whereArgs[2] = source;
String order = "id ASC"; String order = "id ASC";
cursor = db.query("reports",columns,where,whereArgs,null,null,order); cursor = db.query("reports", columns, where, whereArgs, null, null, order);
long reportId; long reportId;
if(cursor.moveToFirst()) { if (cursor.moveToFirst()) {
reportId = cursor.getLong(0); reportId = cursor.getLong(0);
cursor.close(); cursor.close();
} else { } else {
@ -244,8 +242,8 @@ public class DatabaseManager extends SQLiteOpenHelper {
whereArgs[1] = source; whereArgs[1] = source;
order = "creation DESC"; order = "creation DESC";
//search a recent reports //search a recent reports
cursor = db.query("reports",columns,where,whereArgs,null,null,order); cursor = db.query("reports", columns, where, whereArgs, null, null, order);
if(cursor.moveToFirst()) { if (cursor.moveToFirst()) {
reportId = cursor.getLong(0); reportId = cursor.getLong(0);
cursor.close(); cursor.close();
} else { } else {
@ -266,8 +264,8 @@ public class DatabaseManager extends SQLiteOpenHelper {
String[] columns = {"id"}; String[] columns = {"id"};
String where = "package = ?"; String where = "package = ?";
String[] whereArgs = {packageName}; String[] whereArgs = {packageName};
Cursor cursor = db.query("applications",columns,where,whereArgs,null,null,null); Cursor cursor = db.query("applications", columns, where, whereArgs, null, null, null);
if(cursor.moveToFirst()) { if (cursor.moveToFirst()) {
long appId = cursor.getLong(0); long appId = cursor.getLong(0);
cursor.close(); cursor.close();
where = "app_id = ? and version_code = ? and source = ?"; where = "app_id = ? and version_code = ? and source = ?";
@ -276,9 +274,9 @@ public class DatabaseManager extends SQLiteOpenHelper {
whereArgs[1] = String.valueOf(version); whereArgs[1] = String.valueOf(version);
whereArgs[2] = source; whereArgs[2] = source;
String order = "id ASC"; String order = "id ASC";
cursor = db.query("reports",columns,where,whereArgs,null,null,order); cursor = db.query("reports", columns, where, whereArgs, null, null, order);
long reportId; long reportId;
if(cursor.moveToFirst()) { if (cursor.moveToFirst()) {
reportId = cursor.getLong(0); reportId = cursor.getLong(0);
cursor.close(); cursor.close();
} else { } else {
@ -292,8 +290,8 @@ public class DatabaseManager extends SQLiteOpenHelper {
whereArgs[1] = source; whereArgs[1] = source;
order = "creation DESC"; order = "creation DESC";
//search a recent reports //search a recent reports
cursor = db.query("reports",columns,where,whereArgs,null,null,order); cursor = db.query("reports", columns, where, whereArgs, null, null, order);
if(cursor.moveToFirst()) { if (cursor.moveToFirst()) {
reportId = cursor.getLong(0); reportId = cursor.getLong(0);
cursor.close(); cursor.close();
} else { } else {
@ -313,9 +311,9 @@ public class DatabaseManager extends SQLiteOpenHelper {
SQLiteDatabase db = getReadableDatabase(); SQLiteDatabase db = getReadableDatabase();
String where = "id = ?"; String where = "id = ?";
String[] whereArgs = {String.valueOf(reportId)}; String[] whereArgs = {String.valueOf(reportId)};
Cursor cursor = db.query("reports",null,where,whereArgs,null,null,null); Cursor cursor = db.query("reports", null, where, whereArgs, null, null, null);
//get report //get report
if(!cursor.moveToFirst()) { if (!cursor.moveToFirst()) {
cursor.close(); cursor.close();
return null; return null;
} }
@ -326,11 +324,11 @@ public class DatabaseManager extends SQLiteOpenHelper {
long creation = cursor.getLong(col++); long creation = cursor.getLong(col++);
report.creationDate = Calendar.getInstance(); report.creationDate = Calendar.getInstance();
report.creationDate.setTimeInMillis(creation); report.creationDate.setTimeInMillis(creation);
report.creationDate.set(Calendar.MILLISECOND,0); report.creationDate.set(Calendar.MILLISECOND, 0);
long update = cursor.getLong(col++); long update = cursor.getLong(col++);
report.updateDate = Calendar.getInstance(); report.updateDate = Calendar.getInstance();
report.updateDate.setTimeInMillis(update); report.updateDate.setTimeInMillis(update);
report.updateDate.set(Calendar.MILLISECOND,0); report.updateDate.set(Calendar.MILLISECOND, 0);
report.downloads = cursor.getString(col++); report.downloads = cursor.getString(col++);
report.version = cursor.getString(col++); report.version = cursor.getString(col++);
report.versionCode = cursor.getLong(col++); report.versionCode = cursor.getLong(col++);
@ -342,7 +340,7 @@ public class DatabaseManager extends SQLiteOpenHelper {
where = "report_id = ?"; where = "report_id = ?";
String[] columns = {"tracker_id"}; String[] columns = {"tracker_id"};
String order = "tracker_id DESC"; String order = "tracker_id DESC";
cursor = db.query("trackers_reports",columns,where,whereArgs,null,null,order); cursor = db.query("trackers_reports", columns, where, whereArgs, null, null, order);
//get trackersIds //get trackersIds
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
report.trackers.add(cursor.getLong(0)); report.trackers.add(cursor.getLong(0));
@ -355,9 +353,9 @@ public class DatabaseManager extends SQLiteOpenHelper {
String[] columns = {"creator"}; String[] columns = {"creator"};
String where = "id = ?"; String where = "id = ?";
String[] whereArgs = {String.valueOf(applicationId)}; String[] whereArgs = {String.valueOf(applicationId)};
Cursor cursor = getReadableDatabase().query("applications",columns,where,whereArgs,null,null,null); Cursor cursor = getReadableDatabase().query("applications", columns, where, whereArgs, null, null, null);
String creator; String creator;
if(cursor.moveToFirst()) if (cursor.moveToFirst())
creator = cursor.getString(0); creator = cursor.getString(0);
else else
creator = ""; creator = "";
@ -366,13 +364,12 @@ public class DatabaseManager extends SQLiteOpenHelper {
} }
public Tracker getTracker(long trackerId) { public Tracker getTracker(long trackerId) {
SQLiteDatabase db = getReadableDatabase(); SQLiteDatabase db = getReadableDatabase();
String where = "id = ?"; String where = "id = ?";
String[] whereArgs = {String.valueOf(trackerId)}; String[] whereArgs = {String.valueOf(trackerId)};
Cursor cursor = db.query("trackers",null,where,whereArgs,null,null,null,null); Cursor cursor = db.query("trackers", null, where, whereArgs, null, null, null, null);
Tracker tracker = null; Tracker tracker = null;
if(cursor.moveToFirst()) if (cursor.moveToFirst()) {
{
tracker = new Tracker(); tracker = new Tracker();
int col = 0; int col = 0;
tracker.id = cursor.getLong(col++); tracker.id = cursor.getLong(col++);
@ -392,7 +389,7 @@ public class DatabaseManager extends SQLiteOpenHelper {
public Set<Tracker> getTrackers(Set<Long> trackers_id) { public Set<Tracker> getTrackers(Set<Long> trackers_id) {
Set<Tracker> trackers = new HashSet<>(); Set<Tracker> trackers = new HashSet<>();
for(Long trackerId : trackers_id) { for (Long trackerId : trackers_id) {
Tracker tracker = getTracker(trackerId); Tracker tracker = getTracker(trackerId);
trackers.add(tracker); trackers.add(tracker);
} }
@ -401,40 +398,39 @@ public class DatabaseManager extends SQLiteOpenHelper {
void insertOrUpdateTrackers(List<Tracker> trackersList) { void insertOrUpdateTrackers(List<Tracker> trackersList) {
SQLiteDatabase db = getWritableDatabase(); SQLiteDatabase db = getWritableDatabase();
for(Tracker tracker : trackersList) { for (Tracker tracker : trackersList) {
insertOrUpdateTracker(db,tracker); insertOrUpdateTracker(db, tracker);
} }
} }
public Map<String,String> getSources(String packageName) { public Map<String, String> getSources(String packageName) {
String where = "package = ?"; String where = "package = ?";
String[] whereArgs = {packageName}; String[] whereArgs = {packageName};
String[] columns = {"sources"}; String[] columns = {"sources"};
Cursor cursor = getReadableDatabase().query("applications",columns,where,whereArgs,null,null,null,null); Cursor cursor = getReadableDatabase().query("applications", columns, where, whereArgs, null, null, null, null);
String sourcesStr=""; String sourcesStr = "";
if(cursor.moveToFirst()) if (cursor.moveToFirst()) {
{
sourcesStr = cursor.getString(0); sourcesStr = cursor.getString(0);
} }
cursor.close(); cursor.close();
return extractSources(sourcesStr); return extractSources(sourcesStr);
} }
private String buildSourcesStr(Map<String,String> sources) { private String buildSourcesStr(Map<String, String> sources) {
StringBuilder sourceStr = new StringBuilder(); StringBuilder sourceStr = new StringBuilder();
for(Map.Entry<String,String> entry : sources.entrySet()) { for (Map.Entry<String, String> entry : sources.entrySet()) {
sourceStr.append(entry.getKey()).append(":").append(entry.getValue()).append("|"); sourceStr.append(entry.getKey()).append(":").append(entry.getValue()).append("|");
} }
return sourceStr.toString(); return sourceStr.toString();
} }
private Map<String, String> extractSources(String sourcesStr) { private Map<String, String> extractSources(String sourcesStr) {
Map<String,String> sources = new HashMap<>(); Map<String, String> sources = new HashMap<>();
String[] sourceList = sourcesStr.split("\\|"); String[] sourceList = sourcesStr.split("\\|");
for(String sourceItem : sourceList){ for (String sourceItem : sourceList) {
if(!sourceItem.isEmpty()) { if (!sourceItem.isEmpty()) {
String[] data = sourceItem.split(":"); String[] data = sourceItem.split(":");
if(data.length == 2) if (data.length == 2)
sources.put(data[0], data[1]); sources.put(data[0], data[1]);
} }
} }

View File

@ -22,6 +22,12 @@ import android.content.Context;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.os.Bundle; import android.os.Bundle;
import org.eu.exodus_privacy.exodusprivacy.R;
import org.eu.exodus_privacy.exodusprivacy.listener.NetworkListener;
import org.eu.exodus_privacy.exodusprivacy.objects.Application;
import org.eu.exodus_privacy.exodusprivacy.objects.Report;
import org.eu.exodus_privacy.exodusprivacy.objects.Tracker;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -36,9 +42,7 @@ import java.text.DateFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -46,17 +50,9 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import org.eu.exodus_privacy.exodusprivacy.R;
import org.eu.exodus_privacy.exodusprivacy.listener.NetworkListener;
import org.eu.exodus_privacy.exodusprivacy.objects.Application;
import org.eu.exodus_privacy.exodusprivacy.objects.Report;
import org.eu.exodus_privacy.exodusprivacy.objects.Tracker;
/* /*
Singleton that handle all network connection Singleton that handle all network connection
*/ */
@ -80,28 +76,28 @@ public class NetworkManager {
mes.context = context; mes.context = context;
mes.listener = listener; mes.listener = listener;
mes.args = new Bundle(); mes.args = new Bundle();
mes.args.putStringArrayList("packages",packageList); mes.args.putStringArrayList("packages", packageList);
addMessageToQueue(mes); addMessageToQueue(mes);
} }
private void addMessageToQueue(Message mes) {
if (thread == null || thread.getState() == Thread.State.TERMINATED || !thread.isRunning)
thread = new NetworkProcessingThread();
thread.queueMessage(mes);
if (thread.getState() == Thread.State.NEW)
thread.start();
}
private enum Message_Type { private enum Message_Type {
GET_REPORTS, GET_REPORTS,
UNKNOWN UNKNOWN
} }
private void addMessageToQueue(Message mes){
if(thread == null || thread.getState() == Thread.State.TERMINATED || !thread.isRunning)
thread = new NetworkProcessingThread();
thread.queueMessage(mes);
if(thread.getState() == Thread.State.NEW)
thread.start();
}
private class NetworkProcessingThread extends Thread { private class NetworkProcessingThread extends Thread {
private List<Message> messageQueue; private final String apiUrl = "https://reports.exodus-privacy.eu.org/api/";
private Semaphore sem; private final List<Message> messageQueue;
private final Semaphore sem;
boolean isRunning; boolean isRunning;
private final String apiUrl = "https://reports.exodus-privacy.eu.org/api/";
NetworkProcessingThread() { NetworkProcessingThread() {
messageQueue = new ArrayList<>(); messageQueue = new ArrayList<>();
@ -147,7 +143,7 @@ public class NetworkManager {
urlConnection = (HttpURLConnection) url.openConnection(); urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Authorization","Token "+context.getString(R.string.exodus)); urlConnection.setRequestProperty("Authorization", "Token " + context.getString(R.string.exodus));
urlConnection.setDoInput(true); urlConnection.setDoInput(true);
} catch (Exception e) { } catch (Exception e) {
return null; return null;
@ -160,18 +156,17 @@ public class NetworkManager {
inStream = urlConnection.getErrorStream(); inStream = urlConnection.getErrorStream();
} }
JSONObject object = null; JSONObject object = null;
if(success) { if (success) {
String jsonStr = getJSON(inStream); String jsonStr = getJSON(inStream);
try { try {
object = new JSONObject(jsonStr); object = new JSONObject(jsonStr);
} catch (Exception e) } catch (Exception e) {
{
e.printStackTrace(); e.printStackTrace();
} }
} }
try { try {
if(inStream != null) if (inStream != null)
inStream.close(); inStream.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -181,33 +176,36 @@ public class NetworkManager {
} }
private void getTrackers(Message mes) { private void getTrackers(Message mes) {
mes.listener.onProgress(R.string.get_trackers_connection,0,0); mes.listener.onProgress(R.string.get_trackers_connection, 0, 0);
URL url; URL url;
try { try {
url = new URL(apiUrl+"trackers"); url = new URL(apiUrl + "trackers");
} catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
JSONObject object = makeDataRequest(mes.context,mes.listener,url); JSONObject object = makeDataRequest(mes.context, mes.listener, url);
mes.listener.onProgress(R.string.get_trackers,0,0); mes.listener.onProgress(R.string.get_trackers, 0, 0);
if(object != null) { if (object != null) {
try { try {
JSONObject trackers = object.getJSONObject("trackers"); JSONObject trackers = object.getJSONObject("trackers");
List<Tracker> trackersList = new ArrayList<>(); List<Tracker> trackersList = new ArrayList<>();
for(int i = 0; i<trackers.names().length(); i++) { JSONArray trackerNames = trackers.names();
mes.listener.onProgress(R.string.parse_trackers,i+1,trackers.names().length()); if (trackerNames != null) {
String trackerId = trackers.names().get(i).toString(); for (int i = 0; i < trackerNames.length(); i++) {
JSONObject tracker = trackers.getJSONObject(trackerId); mes.listener.onProgress(R.string.parse_trackers, i + 1, trackerNames.length());
Tracker track = parseTracker(tracker,trackerId); String trackerId = trackerNames.get(i).toString();
trackersList.add(track); JSONObject tracker = trackers.getJSONObject(trackerId);
if (trackersList.size() == 20) { Tracker track = parseTracker(tracker, trackerId);
DatabaseManager.getInstance(mes.context).insertOrUpdateTrackers(trackersList); trackersList.add(track);
trackersList.clear(); if (trackersList.size() == 20) {
DatabaseManager.getInstance(mes.context).insertOrUpdateTrackers(trackersList);
trackersList.clear();
}
} }
} }
if(!trackersList.isEmpty()) if (!trackersList.isEmpty())
DatabaseManager.getInstance(mes.context).insertOrUpdateTrackers(trackersList); DatabaseManager.getInstance(mes.context).insertOrUpdateTrackers(trackersList);
trackersList.clear(); trackersList.clear();
} catch (JSONException e) { } catch (JSONException e) {
@ -217,21 +215,20 @@ public class NetworkManager {
} }
private void getApplications(Message mes) { private void getApplications(Message mes) {
mes.listener.onProgress(R.string.get_reports_connection,0,0); mes.listener.onProgress(R.string.get_reports_connection, 0, 0);
URL url; URL url;
try { try {
url = new URL(apiUrl+"applications?option=short"); url = new URL(apiUrl + "applications?option=short");
} catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
JSONObject object = makeDataRequest(mes.context,mes.listener,url); JSONObject object = makeDataRequest(mes.context, mes.listener, url);
mes.listener.onProgress(R.string.get_reports,0,0); mes.listener.onProgress(R.string.get_reports, 0, 0);
if (object != null) {
if(object != null) { Map<String, Map<String, String>> handles = new HashMap<>();
Map<String,Map<String,String>> handles = new HashMap<>();
ArrayList<String> packages = mes.args.getStringArrayList("packages"); ArrayList<String> packages = mes.args.getStringArrayList("packages");
if (packages == null) if (packages == null)
return; return;
@ -240,18 +237,18 @@ public class NetworkManager {
JSONArray applications = object.getJSONArray("applications"); JSONArray applications = object.getJSONArray("applications");
//manage handles map (handle,UAID) //manage handles map (handle,UAID)
for(int i = 0; i<applications.length(); i++) { for (int i = 0; i < applications.length(); i++) {
JSONObject app = applications.getJSONObject(i); JSONObject app = applications.getJSONObject(i);
String handle = app.getString("handle"); String handle = app.getString("handle");
String auid = app.getString("app_uid"); String auid = app.getString("app_uid");
String source = app.getString("source"); String source = app.getString("source");
Map<String,String> sources = handles.get(handle); Map<String, String> sources = handles.get(handle);
if(sources == null) if (sources == null)
sources = new HashMap<>(); sources = new HashMap<>();
sources.put(source,auid); sources.put(source, auid);
if (packages.contains(handle)) if (packages.contains(handle))
handles.put(handle,sources); handles.put(handle, sources);
} }
//remove app not analyzed by Exodus //remove app not analyzed by Exodus
@ -260,11 +257,11 @@ public class NetworkManager {
// Add some random packages to avoid tracking // Add some random packages to avoid tracking
Random rand = new Random(Thread.currentThread().getId()); Random rand = new Random(Thread.currentThread().getId());
int alea = rand.nextInt(120) % 10 + 11; int alea = rand.nextInt(120) % 10 + 11;
for(int i = 0 ; i < alea; i++) { for (int i = 0; i < alea; i++) {
int val = rand.nextInt(applications.length()); int val = rand.nextInt(applications.length());
JSONObject app = applications.getJSONObject(val); JSONObject app = applications.getJSONObject(val);
String handle = app.getString("handle"); String handle = app.getString("handle");
handles.put(handle,new HashMap<>()); handles.put(handle, new HashMap<>());
packages.add(handle); packages.add(handle);
} }
//shuffle the list //shuffle the list
@ -276,33 +273,33 @@ public class NetworkManager {
mes.listener.onError(mes.context.getString(R.string.json_error)); mes.listener.onError(mes.context.getString(R.string.json_error));
} }
object = null; object = null;
getReports(mes,handles,packages); getReports(mes, handles, packages);
} }
mes.listener.onSuccess(); mes.listener.onSuccess();
} }
private void getReports(Message mes, Map<String, Map<String,String>> handles, ArrayList<String> packages) { private void getReports(Message mes, Map<String, Map<String, String>> handles, ArrayList<String> packages) {
for(int i = 0; i < packages.size(); i++) { for (int i = 0; i < packages.size(); i++) {
mes.listener.onProgress(R.string.parse_application,i+1,packages.size()); mes.listener.onProgress(R.string.parse_application, i + 1, packages.size());
getReport(mes,packages.get(i),handles.get(packages.get(i))); getReport(mes, packages.get(i), handles.get(packages.get(i)));
} }
} }
private void getReport(Message mes, String handle, Map<String,String> sources) { private void getReport(Message mes, String handle, Map<String, String> sources) {
URL url; URL url;
try { try {
url = new URL(apiUrl+"search/"+handle); url = new URL(apiUrl + "search/" + handle);
} catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
JSONObject object = makeDataRequest(mes.context,mes.listener,url); JSONObject object = makeDataRequest(mes.context, mes.listener, url);
if(object != null) { if (object != null) {
try { try {
JSONObject application = object.getJSONObject(handle); JSONObject application = object.getJSONObject(handle);
ArrayList<String> packages = mes.args.getStringArrayList("packages"); ArrayList<String> packages = mes.args.getStringArrayList("packages");
if(packages != null && packages.contains(handle)) { if (packages != null && packages.contains(handle)) {
Application app = parseApplication(application, handle); Application app = parseApplication(application, handle);
app.sources = sources; app.sources = sources;
DatabaseManager.getInstance(mes.context).insertOrUpdateApplication(app); DatabaseManager.getInstance(mes.context).insertOrUpdateApplication(app);
@ -322,7 +319,7 @@ public class NetworkManager {
//parse Report //parse Report
application.reports = new HashSet<>(); application.reports = new HashSet<>();
JSONArray reports = object.getJSONArray("reports"); JSONArray reports = object.getJSONArray("reports");
for(int i = 0; i < reports.length(); i++) { for (int i = 0; i < reports.length(); i++) {
Report report = parseReport(reports.getJSONObject(i)); Report report = parseReport(reports.getJSONObject(i));
application.reports.add(report); application.reports.add(report);
} }
@ -335,25 +332,25 @@ public class NetworkManager {
report.downloads = object.getString("downloads"); report.downloads = object.getString("downloads");
report.version = object.getString("version"); report.version = object.getString("version");
report.source = object.getString("source"); report.source = object.getString("source");
if(!object.getString("version_code").isEmpty()) if (!object.getString("version_code").isEmpty())
report.versionCode = Long.parseLong(object.getString("version_code")); report.versionCode = Long.parseLong(object.getString("version_code"));
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
try { try {
report.updateDate = Calendar.getInstance(); report.updateDate = Calendar.getInstance();
report.updateDate.setTimeZone(TimeZone.getTimeZone("UTC")); report.updateDate.setTimeZone(TimeZone.getTimeZone("UTC"));
report.updateDate.setTime(dateFormat.parse(object.getString("updated_at"))); report.updateDate.setTime(dateFormat.parse(object.getString("updated_at")));
report.updateDate.set(Calendar.MILLISECOND,0); report.updateDate.set(Calendar.MILLISECOND, 0);
report.creationDate = Calendar.getInstance(); report.creationDate = Calendar.getInstance();
report.creationDate.setTimeZone(TimeZone.getTimeZone("UTC")); report.creationDate.setTimeZone(TimeZone.getTimeZone("UTC"));
report.creationDate.setTime(dateFormat.parse(object.getString("creation_date"))); report.creationDate.setTime(dateFormat.parse(object.getString("creation_date")));
report.creationDate.set(Calendar.MILLISECOND,0); report.creationDate.set(Calendar.MILLISECOND, 0);
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} }
JSONArray trackersArray = object.getJSONArray("trackers"); JSONArray trackersArray = object.getJSONArray("trackers");
report.trackers = new HashSet<>(); report.trackers = new HashSet<>();
for(int i = 0; i < trackersArray.length(); i++) for (int i = 0; i < trackersArray.length(); i++)
report.trackers.add(trackersArray.getLong(i)); report.trackers.add(trackersArray.getLong(i));
return report; return report;
} }
@ -402,20 +399,18 @@ public class NetworkManager {
private boolean isConnectedToInternet(Context context) { private boolean isConnectedToInternet(Context context) {
//verify the connectivity //verify the connectivity
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager == null) if (connectivityManager == null)
return false; return false;
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) { if (networkInfo != null) {
NetworkInfo.State networkState = networkInfo.getState(); NetworkInfo.State networkState = networkInfo.getState();
if (networkState.equals(NetworkInfo.State.CONNECTED)) { return networkState.equals(NetworkInfo.State.CONNECTED);
return true;
}
} }
return false; return false;
} }
} }
private class Message{ private class Message {
Message_Type type = Message_Type.UNKNOWN; Message_Type type = Message_Type.UNKNOWN;
Bundle args = new Bundle(); Bundle args = new Bundle();
NetworkListener listener; NetworkListener listener;

View File

@ -19,7 +19,6 @@
package org.eu.exodus_privacy.exodusprivacy.objects; package org.eu.exodus_privacy.exodusprivacy.objects;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
public class Application { public class Application {
@ -28,7 +27,7 @@ public class Application {
public String name; public String name;
public String creator; public String creator;
public Set<Report> reports; public Set<Report> reports;
public Map<String,String> sources; public Map<String, String> sources;
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {

View File

@ -7,7 +7,6 @@ import android.content.pm.PackageManager;
import android.content.pm.PermissionGroupInfo; import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo; import android.content.pm.PermissionInfo;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.Build;
import org.eu.exodus_privacy.exodusprivacy.R; import org.eu.exodus_privacy.exodusprivacy.R;
import org.eu.exodus_privacy.exodusprivacy.adapters.ApplicationViewModel; import org.eu.exodus_privacy.exodusprivacy.adapters.ApplicationViewModel;
@ -31,7 +30,7 @@ public class ReportDisplay {
public String viewOnStore; public String viewOnStore;
private ReportDisplay(){ private ReportDisplay() {
} }
@ -43,32 +42,32 @@ public class ReportDisplay {
reportDisplay.displayName = model.label.toString(); reportDisplay.displayName = model.label.toString();
reportDisplay.report = model.report; reportDisplay.report = model.report;
reportDisplay.source = context.getString(R.string.source,model.source); reportDisplay.source = context.getString(R.string.source, model.source);
reportDisplay.viewOnStore = context.getString(model.source.equals("google")? R.string.view_on_google_play : R.string.view_on_fdroid); reportDisplay.viewOnStore = context.getString(model.source.equals("google") ? R.string.view_on_google_play : R.string.view_on_fdroid);
reportDisplay.trackers = model.trackers; reportDisplay.trackers = model.trackers;
if (reportDisplay.report != null) if (reportDisplay.report != null)
reportDisplay.creator = DatabaseManager.getInstance(context).getCreator(reportDisplay.report.appId); reportDisplay.creator = DatabaseManager.getInstance(context).getCreator(reportDisplay.report.appId);
List<Permission> requestedPermissions= new ArrayList<>(); List<Permission> requestedPermissions = new ArrayList<>();
if (info.requestedPermissions != null) { if (info.requestedPermissions != null) {
for(int i = 0; i < info.requestedPermissions.length; i++) { for (int i = 0; i < info.requestedPermissions.length; i++) {
Permission permission = new Permission(); Permission permission = new Permission();
permission.fullName = info.requestedPermissions[i]; permission.fullName = info.requestedPermissions[i];
try { try {
PermissionInfo permissionInfo = manager.getPermissionInfo(permission.fullName,PackageManager.GET_META_DATA); PermissionInfo permissionInfo = manager.getPermissionInfo(permission.fullName, PackageManager.GET_META_DATA);
if(permissionInfo.loadDescription(manager) != null) if (permissionInfo.loadDescription(manager) != null)
permission.description = permissionInfo.loadDescription(manager).toString(); permission.description = permissionInfo.loadDescription(manager).toString();
if(permissionInfo.loadLabel(manager) != null) if (permissionInfo.loadLabel(manager) != null)
permission.name = permissionInfo.loadLabel(manager).toString(); permission.name = permissionInfo.loadLabel(manager).toString();
permission.dangerous = permissionInfo.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS; permission.dangerous = permissionInfo.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS;
if(permission.fullName.equals(Manifest.permission.WRITE_SETTINGS) || permission.fullName.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) //Special permissions if (permission.fullName.equals(Manifest.permission.WRITE_SETTINGS) || permission.fullName.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) //Special permissions
permission.dangerous = true; permission.dangerous = true;
if (permissionInfo.group != null) { if (permissionInfo.group != null) {
PermissionGroupInfo permissionGroupInfo = manager.getPermissionGroupInfo(permissionInfo.group, PackageManager.GET_META_DATA); PermissionGroupInfo permissionGroupInfo = manager.getPermissionGroupInfo(permissionInfo.group, PackageManager.GET_META_DATA);
if(permissionGroupInfo.loadIcon(manager) != null) if (permissionGroupInfo.loadIcon(manager) != null)
permission.icon = permissionGroupInfo.loadIcon(manager); permission.icon = permissionGroupInfo.loadIcon(manager);
} }

View File

@ -9,7 +9,7 @@ buildscript {
google() google()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:4.0.0' classpath 'com.android.tools.build:gradle:4.1.0'
// NOTE: Do not place your application dependencies here; they belong // NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files // in the individual module build.gradle files

View File

@ -1,6 +1,6 @@
#Tue Jul 07 01:06:44 CEST 2020 #Mon Dec 07 08:49:24 CET 2020
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip