Browse Source

Rebase and cleanup

pull/24/head
Apostolos Fanakis 8 years ago
parent
commit
0f74cef501
  1. 32
      app/src/main/AndroidManifest.xml
  2. 20
      app/src/main/java/gr/thmmy/mthmmy/activities/AboutActivity.java
  3. 8
      app/src/main/java/gr/thmmy/mthmmy/activities/BookmarkActivity.java
  4. 19
      app/src/main/java/gr/thmmy/mthmmy/activities/board/BoardActivity.java
  5. 4
      app/src/main/java/gr/thmmy/mthmmy/activities/downloads/DownloadsActivity.java
  6. 8
      app/src/main/java/gr/thmmy/mthmmy/activities/downloads/DownloadsAdapter.java
  7. 5
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java
  8. 85
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java
  9. 2
      app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicParser.java
  10. 12
      app/src/main/java/gr/thmmy/mthmmy/base/BaseActivity.java
  11. 2
      app/src/main/java/gr/thmmy/mthmmy/model/Post.java
  12. 37
      app/src/main/java/gr/thmmy/mthmmy/model/ThmmyFile.java
  13. 256
      app/src/main/java/gr/thmmy/mthmmy/utils/FileManager/ThmmyFile.java
  14. BIN
      app/src/main/res/drawable-hdpi/ic_pin.png
  15. BIN
      app/src/main/res/drawable-hdpi/ic_remove_circle.png
  16. BIN
      app/src/main/res/drawable-mdpi/ic_pin.png
  17. BIN
      app/src/main/res/drawable-mdpi/ic_remove_circle.png
  18. BIN
      app/src/main/res/drawable-xhdpi/ic_pin.png
  19. BIN
      app/src/main/res/drawable-xhdpi/ic_remove_circle.png
  20. BIN
      app/src/main/res/drawable-xxhdpi/ic_pin.png
  21. BIN
      app/src/main/res/drawable-xxhdpi/ic_remove_circle.png
  22. BIN
      app/src/main/res/drawable-xxxhdpi/ic_pin.png
  23. BIN
      app/src/main/res/drawable-xxxhdpi/ic_remove_circle.png

32
app/src/main/AndroidManifest.xml

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gr.thmmy.mthmmy">
package="gr.thmmy.mthmmy">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:name=".base.BaseApplication"
@ -22,9 +22,9 @@
android:launchMode="singleTask"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
@ -33,14 +33,14 @@
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar"
android:windowSoftInputMode="adjustPan"></activity>
android:windowSoftInputMode="adjustPan"/>
<activity
android:name=".activities.AboutActivity"
android:parentActivityName=".activities.main.MainActivity"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.main.MainActivity" />
android:value=".activities.main.MainActivity"/>
</activity>
<activity
android:name=".activities.topic.TopicActivity"
@ -49,11 +49,11 @@
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.main.MainActivity" />
android:value=".activities.main.MainActivity"/>
</activity>
<activity
android:name=".activities.profile.ProfileActivity"
android:theme="@style/AppTheme.NoActionBar"></activity>
android:theme="@style/AppTheme.NoActionBar"/>
<activity
android:name=".activities.board.BoardActivity"
android:configChanges="orientation|screenSize"
@ -61,7 +61,7 @@
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.main.MainActivity" />
android:value=".activities.main.MainActivity"/>
</activity>
<activity
android:name=".activities.downloads.DownloadsActivity"
@ -69,7 +69,7 @@
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.main.MainActivity" />
android:value=".activities.main.MainActivity"/>
</activity>
<activity
android:name=".activities.BookmarkActivity"
@ -77,7 +77,7 @@
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.main.MainActivity" />
android:value=".activities.main.MainActivity"/>
</activity>
<provider
@ -87,12 +87,12 @@
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
android:resource="@xml/provider_paths"/>
</provider>
<service
android:name=".services.DownloadService"
android:exported="false"></service>
android:exported="false"/>
</application>
</manifest>

20
app/src/main/java/gr/thmmy/mthmmy/activities/AboutActivity.java

@ -26,7 +26,7 @@ public class AboutActivity extends BaseActivity {
private AppBarLayout appBar;
private CoordinatorLayout coordinatorLayout;
AlertDialog alertDialog;
private AlertDialog alertDialog;
private FrameLayout trollGif;
@Override
@ -42,8 +42,10 @@ public class AboutActivity extends BaseActivity {
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.about);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
createDrawer();
drawer.setSelection(ABOUT_ID);
@ -84,11 +86,11 @@ public class AboutActivity extends BaseActivity {
}
public void displayApacheLibraries(View v) {
LayoutInflater inflater =LayoutInflater.from(this);
LayoutInflater inflater = LayoutInflater.from(this);
WebView webView = (WebView) inflater.inflate(R.layout.dialog_licenses, coordinatorLayout, false);
webView.loadUrl("file:///android_asset/apache_libraries.html");
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.95);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.95);
int width = (int) (getResources().getDisplayMetrics().widthPixels * 0.95);
int height = (int) (getResources().getDisplayMetrics().heightPixels * 0.95);
alertDialog = new AlertDialog.Builder(this, R.style.AppTheme_Dark_Dialog)
.setTitle(getString(R.string.apache_v2_0_libraries))
.setView(webView)
@ -98,11 +100,11 @@ public class AboutActivity extends BaseActivity {
}
public void displayMITLibraries(View v) {
LayoutInflater inflater =LayoutInflater.from(this);
LayoutInflater inflater = LayoutInflater.from(this);
WebView webView = (WebView) inflater.inflate(R.layout.dialog_licenses, coordinatorLayout, false);
webView.loadUrl("file:///android_asset/mit_libraries.html");
int width = (int)(getResources().getDisplayMetrics().widthPixels*0.95);
int height = (int)(getResources().getDisplayMetrics().heightPixels*0.95);
int width = (int) (getResources().getDisplayMetrics().widthPixels * 0.95);
int height = (int) (getResources().getDisplayMetrics().heightPixels * 0.95);
alertDialog = new AlertDialog.Builder(this, R.style.AppTheme_Dark_Dialog)
.setTitle(getString(R.string.the_mit_libraries))
.setView(webView)

8
app/src/main/java/gr/thmmy/mthmmy/activities/BookmarkActivity.java

@ -5,7 +5,6 @@ import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
@ -25,7 +24,6 @@ import static gr.thmmy.mthmmy.activities.topic.TopicActivity.BUNDLE_TOPIC_TITLE;
import static gr.thmmy.mthmmy.activities.topic.TopicActivity.BUNDLE_TOPIC_URL;
public class BookmarkActivity extends BaseActivity {
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -43,7 +41,6 @@ public class BookmarkActivity extends BaseActivity {
createDrawer();
drawer.setSelection(BOOKMARKS_ID);
progressBar = (MaterialProgressBar) findViewById(R.id.progressBar);
LinearLayout bookmarksLinearView = (LinearLayout) findViewById(R.id.bookmarks_container);
LayoutInflater layoutInflater = getLayoutInflater();
@ -66,15 +63,11 @@ public class BookmarkActivity extends BaseActivity {
for (final Bookmark bookmarkedBoard : getBoardsBookmarked()) {
if (bookmarkedBoard != null && bookmarkedBoard.getTitle() != null) {
Log.d("TAG", bookmarkedBoard.getTitle() + " - " + bookmarkedBoard.getId());
final LinearLayout row = (LinearLayout) layoutInflater.inflate(
R.layout.activity_bookmark_row, bookmarksLinearView, false);
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("TAG", "https://www.thmmy.gr/smf/index.php?board="
+ bookmarkedBoard.getId() + ".0");
Log.d("TAG", bookmarkedBoard.getTitle());
Intent intent = new Intent(BookmarkActivity.this, BoardActivity.class);
Bundle extras = new Bundle();
extras.putString(BUNDLE_BOARD_URL, "https://www.thmmy.gr/smf/index.php?board="
@ -115,7 +108,6 @@ public class BookmarkActivity extends BaseActivity {
for (final Bookmark bookmarkedTopic : getTopicsBookmarked()) {
if (bookmarkedTopic != null && bookmarkedTopic.getTitle() != null) {
Log.d("TAG", bookmarkedTopic.getTitle() + " - " + bookmarkedTopic.getId());
final LinearLayout row = (LinearLayout) layoutInflater.inflate(
R.layout.activity_bookmark_row, bookmarksLinearView, false);
row.setOnClickListener(new View.OnClickListener() {

19
app/src/main/java/gr/thmmy/mthmmy/activities/board/BoardActivity.java

@ -181,7 +181,7 @@ public class BoardActivity extends BaseActivity implements BoardAdapter.OnLoadMo
* <p>BoardTask's {@link AsyncTask#execute execute} method needs a boards's url as String
* parameter!</p>
*/
public class BoardTask extends AsyncTask<String, Void, Boolean> {
public class BoardTask extends AsyncTask<String, Void, Void> {
//Class variables
/**
* Debug Tag for logging debug output to LogCat
@ -196,29 +196,23 @@ public class BoardActivity extends BaseActivity implements BoardAdapter.OnLoadMo
}
@Override
protected Boolean doInBackground(String... boardUrl) {
protected Void doInBackground(String... boardUrl) {
Request request = new Request.Builder()
.url(boardUrl[0])
.build();
try {
Response response = BaseActivity.getClient().newCall(request).execute();
return parseBoard(Jsoup.parse(response.body().string()));
parseBoard(Jsoup.parse(response.body().string()));
} catch (SSLHandshakeException e) {
Report.w(TAG, "Certificate problem (please switch to unsafe connection).");
} catch (Exception e) {
Report.e("TAG", "ERROR", e);
}
return false;
return null;
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) { //Parse failed!
Report.d(TAG, "Parse failed!");
Toast.makeText(getApplicationContext()
, "Fatal error!\n Aborting...", Toast.LENGTH_LONG).show();
finish();
}
protected void onPostExecute(Void voids) {
if (boardTitle == null || Objects.equals(boardTitle, "")) toolbar.setTitle(boardTitle);
//Parse was successful
@ -229,7 +223,7 @@ public class BoardActivity extends BaseActivity implements BoardAdapter.OnLoadMo
isLoadingMore = false;
}
private boolean parseBoard(Document boardPage) {
private void parseBoard(Document boardPage) {
if (boardTitle == null || Objects.equals(boardTitle, ""))
boardTitle = boardPage.select("div.nav a.nav").last().text();
@ -333,7 +327,6 @@ public class BoardActivity extends BaseActivity implements BoardAdapter.OnLoadMo
}
}
}
return true;
}
}
}

4
app/src/main/java/gr/thmmy/mthmmy/activities/downloads/DownloadsActivity.java

@ -47,8 +47,8 @@ public class DownloadsActivity extends BaseActivity implements DownloadsAdapter.
public static final String BUNDLE_DOWNLOADS_TITLE = "DOWNLOADS_TITLE";
private static final String downloadsIndexUrl = "https://www.thmmy.gr/smf/index.php?action=tpmod;dl;";
private String downloadsUrl;
String downloadsTitle;
private ArrayList<Download> parsedDownloads = new ArrayList<>();
private String downloadsTitle;
private final ArrayList<Download> parsedDownloads = new ArrayList<>();
private MaterialProgressBar progressBar;
private RecyclerView recyclerView;

8
app/src/main/java/gr/thmmy/mthmmy/activities/downloads/DownloadsAdapter.java

@ -3,6 +3,7 @@ package gr.thmmy.mthmmy.activities.downloads;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
@ -125,7 +126,12 @@ class DownloadsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
} else {
//TODO implement download on click
downloadViewHolder.upperLinear.setBackgroundColor(context.getResources().getColor(R.color.background));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
downloadViewHolder.upperLinear.setBackgroundColor(context.getResources().getColor(R.color.background, null));
} else {
//noinspection deprecation
downloadViewHolder.upperLinear.setBackgroundColor(context.getResources().getColor(R.color.background));
}
downloadViewHolder.informationExpandable.setVisibility(View.VISIBLE);
downloadViewHolder.informationExpandableBtn.setVisibility(View.GONE);
downloadViewHolder.informationExpandableBtn.setEnabled(false);

5
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicActivity.java

@ -9,7 +9,6 @@ import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
@ -87,7 +86,7 @@ public class TopicActivity extends BaseActivity {
//Other variables
private FloatingActionButton replyFAB;
private MaterialProgressBar progressBar;
public static String base_url = "";
private static String base_url = "";
private String topicTitle;
private String parsedTitle;
private RecyclerView recyclerView;
@ -132,7 +131,7 @@ public class TopicActivity extends BaseActivity {
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
topicAdapter = new TopicAdapter(this, progressBar, postsList,
topicAdapter = new TopicAdapter(this, postsList,
topicTask);
recyclerView.setAdapter(topicAdapter);

85
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicAdapter.java

@ -7,11 +7,9 @@ import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
@ -20,7 +18,6 @@ import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@ -30,12 +27,9 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@ -47,8 +41,7 @@ import gr.thmmy.mthmmy.base.BaseActivity;
import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.model.ThmmyPage;
import gr.thmmy.mthmmy.utils.CircleTransform;
import gr.thmmy.mthmmy.utils.FileManager.ThmmyFile;
import me.zhanghai.android.materialprogressbar.MaterialProgressBar;
import gr.thmmy.mthmmy.model.ThmmyFile;
import mthmmy.utils.Report;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
@ -93,8 +86,6 @@ class TopicAdapter extends RecyclerView.Adapter<TopicAdapter.MyViewHolder> {
* Index of state indicator in the boolean array. If true quote button for this post is checked.
*/
private static final int isQuoteButtonChecked = 2;
//private final MaterialProgressBar progressBar;
private DownloadTask downloadTask;
private TopicActivity.TopicTask topicTask;
/**
@ -157,7 +148,7 @@ class TopicAdapter extends RecyclerView.Adapter<TopicAdapter.MyViewHolder> {
* @param context the context of the {@link RecyclerView}
* @param postsList List of {@link Post} objects to use
*/
TopicAdapter(Context context, MaterialProgressBar progressBar, List<Post> postsList,
TopicAdapter(Context context, List<Post> postsList,
TopicActivity.TopicTask topicTask) {
this.context = context;
this.postsList = postsList;
@ -167,8 +158,6 @@ class TopicAdapter extends RecyclerView.Adapter<TopicAdapter.MyViewHolder> {
//Initializes properties, array's values will be false by default
viewProperties.add(new boolean[3]);
}
//this.progressBar = progressBar;
downloadTask = new DownloadTask();
this.topicTask = topicTask;
}
@ -632,74 +621,4 @@ class TopicAdapter extends RecyclerView.Adapter<TopicAdapter.MyViewHolder> {
return context.getResources().getString(R.string.fa_file);
}
private class DownloadTask extends AsyncTask<ThmmyFile, Void, String> {
//Class variables
/**
* Debug Tag for logging debug output to LogCat
*/
private static final String TAG = "DownloadTask"; //Separate tag for AsyncTask
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Downloading", Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(ThmmyFile... file) {
try {
File tempFile = file[0].download(context);
if (tempFile != null) {
if (file[0].isInternal()) {
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
file[0].getExtension());
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
//intent.setDataAndType(Uri.fromFile(tempFile), mime);
intent.setDataAndType(FileProvider.getUriForFile(context, context.
getApplicationContext()
.getPackageName() + ".provider", tempFile), mime);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
file[0].getExtension());
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(tempFile), mime);
/*intent.setDataAndType(FileProvider.getUriForFile(context, context.
getApplicationContext()
.getPackageName() + ".provider", tempFile), mime);*/
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
} catch (IOException e) {
Report.e(TAG, "Error while trying to download a file", e);
return e.toString();
} catch (OutOfMemoryError e) {
Report.e(TAG, e.toString(), e);
return e.toString();
} catch (IllegalStateException e) {
Report.e(TAG, e.toString(), e);
return e.toString();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(context, "Download failed!", Toast.LENGTH_SHORT).show();
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
}

2
app/src/main/java/gr/thmmy/mthmmy/activities/topic/TopicParser.java

@ -15,7 +15,7 @@ import java.util.List;
import java.util.Objects;
import gr.thmmy.mthmmy.model.Post;
import gr.thmmy.mthmmy.utils.FileManager.ThmmyFile;
import gr.thmmy.mthmmy.model.ThmmyFile;
import gr.thmmy.mthmmy.utils.ParseHelpers;
import mthmmy.utils.Report;

12
app/src/main/java/gr/thmmy/mthmmy/base/BaseActivity.java

@ -41,7 +41,7 @@ import gr.thmmy.mthmmy.activities.profile.ProfileActivity;
import gr.thmmy.mthmmy.model.Bookmark;
import gr.thmmy.mthmmy.services.DownloadService;
import gr.thmmy.mthmmy.session.SessionManager;
import gr.thmmy.mthmmy.utils.FileManager.ThmmyFile;
import gr.thmmy.mthmmy.model.ThmmyFile;
import okhttp3.OkHttpClient;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
@ -66,11 +66,11 @@ public abstract class BaseActivity extends AppCompatActivity {
private static final String BOOKMARKED_BOARDS_KEY = "bookmarkedBoardsKey";
protected Bookmark thisPageBookmark;
protected ImageButton thisPageBookmarkButton;
protected SharedPreferences bookmarksFile;
protected ArrayList<Bookmark> topicsBookmarked;
protected ArrayList<Bookmark> boardsBookmarked;
protected static Drawable bookmarked;
protected static Drawable notBookmarked;
private SharedPreferences bookmarksFile;
private ArrayList<Bookmark> topicsBookmarked;
private ArrayList<Bookmark> boardsBookmarked;
private static Drawable bookmarked;
private static Drawable notBookmarked;
//Common UI elements
protected Toolbar toolbar;

2
app/src/main/java/gr/thmmy/mthmmy/model/Post.java

@ -5,8 +5,6 @@ import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Objects;
import gr.thmmy.mthmmy.utils.FileManager.ThmmyFile;
/**
* Class that defines a topic's post. All member variables are declared final (thus no setters are
* supplied). Class has two constructors and getter methods for all variables.

37
app/src/main/java/gr/thmmy/mthmmy/model/ThmmyFile.java

@ -0,0 +1,37 @@
package gr.thmmy.mthmmy.model;
import java.net.URL;
public class ThmmyFile {
/**
* Debug Tag for logging debug output to LogCat
*/
private static final String TAG = "ThmmyFile";
private final URL fileUrl;
private final String filename, fileInfo;
/**
* This constructor only creates a ThmmyFile object and <b>does not download</b> the file.
*
* @param fileUrl {@link URL} object with file's url
* @param filename {@link String} with desired file name
* @param fileInfo {@link String} with any extra information (like number of downloads)
*/
public ThmmyFile(URL fileUrl, String filename, String fileInfo) {
this.fileUrl = fileUrl;
this.filename = filename;
this.fileInfo = fileInfo;
}
public URL getFileUrl() {
return fileUrl;
}
public String getFilename() {
return filename;
}
public String getFileInfo() {
return fileInfo;
}
}

256
app/src/main/java/gr/thmmy/mthmmy/utils/FileManager/ThmmyFile.java

@ -1,256 +0,0 @@
package gr.thmmy.mthmmy.utils.FileManager;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import gr.thmmy.mthmmy.base.BaseActivity;
import mthmmy.utils.Report;
import okhttp3.Request;
import okhttp3.Response;
import static android.content.Context.MODE_PRIVATE;
import static gr.thmmy.mthmmy.base.BaseActivity.getClient;
/**
* Used for downloading and storing a file from the forum using {@link okhttp3}.
* <p>Class has one constructor, {@link #ThmmyFile(URL, String, String)}.
*/
@SuppressWarnings("unused")
public class ThmmyFile {
/**
* Debug Tag for logging debug output to LogCat
*/
private static final String TAG = "ThmmyFile";
private final URL fileUrl;
private final String filename, fileInfo;
private String extension, filePath;
private File file;
private boolean isInternal;
/**
* This constructor only creates a empty ThmmyFile object and <b>does not download</b> the file. To download
* the file use {@link #download(Context)} after setting file's url!
*/
public ThmmyFile() {
this.fileUrl = null;
this.filename = null;
this.fileInfo = null;
this.extension = null;
this.filePath = null;
this.file = null;
this.isInternal = false;
}
/**
* This constructor only creates a ThmmyFile object and <b>does not download</b> the file. To
* download the file use {@link #download(Context)} after you provide a url!
*
* @param fileUrl {@link URL} object with file's url
* @param filename {@link String} with desired file name
* @param fileInfo {@link String} with any extra information (like number of downloads)
*/
public ThmmyFile(URL fileUrl, String filename, String fileInfo) {
this.fileUrl = fileUrl;
this.filename = filename;
this.fileInfo = fileInfo;
this.extension = null;
this.filePath = null;
this.file = null;
this.isInternal = false;
}
public URL getFileUrl() {
return fileUrl;
}
public String getFilename() {
return filename;
}
public String getFileInfo() {
return fileInfo;
}
/**
* This is null until {@link #download(Context)} is called and has succeeded.
*
* @return String with file's extension or null
*/
@Nullable
public String getExtension() {
return extension;
}
/**
* This is null until {@link #download(Context)} is called and has succeeded.
*
* @return String with file's path or null
*/
@Nullable
public String getFilePath() {
return filePath;
}
/**
* This is null until {@link #download(Context)} is called and has succeeded.
*
* @return {@link File} or null
*/
@Nullable
public File getFile() {
return file;
}
private void setExtension(String extension) {
this.extension = extension;
}
private void setFilePath(String filePath) {
this.filePath = filePath;
}
public boolean isInternal() {
return isInternal;
}
/**
* Used to download the file. If download is successful file's extension and path will be assigned
* to object's fields and can be accessed using getter methods.
*
* @return null if downloaded with the download service, otherwise the {@link File}
* @throws IOException if the request could not be executed due to cancellation, a
* connectivity problem or timeout. Because networks can fail
* during an exchange, it is possible that the remote server
* accepted the request before the failure.
* @throws SecurityException if the requested file is not hosted by the forum.
* @throws IllegalStateException if file's url or filename is not yet set
*/
@Nullable
public File download(Context context) throws IOException, IllegalStateException, OutOfMemoryError {
if (fileUrl == null)
throw new IllegalStateException("Internal error!\nNo url was provided.");
else if (!Objects.equals(fileUrl.getHost(), "www.thmmy.gr"))
throw new SecurityException("Downloading files from other sources is not supported");
else if (filename == null || Objects.equals(filename, ""))
throw new IllegalStateException("Internal error!\nNo filename was provided.");
return downloadWithoutManager(context, fileUrl);
/*try {
downloadWithManager(context, fileUrl);
} catch (IllegalStateException e) {
return downloadWithoutManager(context, fileUrl);
}*/
//return null;
}
private void downloadWithManager(Context context, @NonNull URL pFileUrl) throws IllegalStateException, IOException {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(pFileUrl.toString()));
request.addRequestHeader("Cookie", BaseActivity.getSessionManager().getCookieHeader());
request.setDescription("mThmmy");
request.setMimeType(MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(filename)));
request.setTitle(filename);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
try {
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
} catch (IllegalStateException e) {
Report.d(TAG, "External directory not available!", e);
throw e;
}
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Download complete", Toast.LENGTH_SHORT).show();
context.unregisterReceiver(this);
}
}, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Nullable
private File downloadWithoutManager(Context context, @NonNull URL pFileUrl) throws IOException
, SecurityException, OutOfMemoryError {
Request request = new Request.Builder().url(pFileUrl).build();
Response response = getClient().newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Failed to download file: " + response);
}
file = getOutputMediaFile(context, filename, fileInfo);
if (file == null) {
Report.d(TAG, "Error creating media file, check storage permissions!");
} else {
FileOutputStream fos;
if (isInternal)
fos = context.openFileOutput(filename, MODE_PRIVATE);
else
fos = new FileOutputStream(file);
fos.write(response.body().bytes());
fos.close();
filePath = file.getAbsolutePath();
extension = MimeTypeMap.getFileExtensionFromUrl(
filePath.substring(filePath.lastIndexOf("/")));
}
return file;
}
@Nullable
private File getOutputMediaFile(Context context, String fileName, String fileInfo) throws
OutOfMemoryError, IOException {
File mediaStorageDir;
String extState = Environment.getExternalStorageState();
if (Environment.isExternalStorageRemovable() &&
Objects.equals(extState, Environment.MEDIA_MOUNTED)) {
mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS), fileName);
} else {
mediaStorageDir = new File(context.getFilesDir(), "Downloads");
isInternal = true;
}
//Creates the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Report.d(TAG, "problem!");
throw new IOException("Error.\nCouldn't create the path!");
}
}
if (fileInfo != null) {
if (fileInfo.contains("KB")) {
float fileSize = Float.parseFloat(fileInfo
.substring(fileInfo.indexOf("(") + 1, fileInfo.indexOf("KB") - 1));
StatFs stat = new StatFs(mediaStorageDir.getPath());
long bytesAvailable = stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
if ((bytesAvailable / 1024.f) < fileSize)
throw new OutOfMemoryError("There is not enough memory!");
}
}
//Creates a media file name
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + fileName);
return mediaFile;
}
}

BIN
app/src/main/res/drawable-hdpi/ic_pin.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 237 B

BIN
app/src/main/res/drawable-hdpi/ic_remove_circle.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 584 B

BIN
app/src/main/res/drawable-mdpi/ic_pin.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 208 B

BIN
app/src/main/res/drawable-mdpi/ic_remove_circle.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 B

BIN
app/src/main/res/drawable-xhdpi/ic_pin.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 266 B

BIN
app/src/main/res/drawable-xhdpi/ic_remove_circle.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 746 B

BIN
app/src/main/res/drawable-xxhdpi/ic_pin.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 344 B

BIN
app/src/main/res/drawable-xxhdpi/ic_remove_circle.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
app/src/main/res/drawable-xxxhdpi/ic_pin.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 408 B

BIN
app/src/main/res/drawable-xxxhdpi/ic_remove_circle.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Loading…
Cancel
Save