Added Android code
[wl-app.git] / Android / r2-streamer / sample / src / main / java / org / readium / sample / TestActivity.java
1 package org.readium.sample;
2
3 import android.Manifest;
4 import android.app.ProgressDialog;
5 import android.content.Intent;
6 import android.content.pm.PackageManager;
7 import android.net.Uri;
8 import android.os.AsyncTask;
9 import android.os.Bundle;
10 import android.os.Environment;
11 import android.support.annotation.NonNull;
12 import android.support.v4.app.ActivityCompat;
13 import android.support.v4.content.ContextCompat;
14 import android.support.v7.app.AppCompatActivity;
15 import android.util.Log;
16 import android.view.View;
17 import android.widget.AdapterView;
18 import android.widget.EditText;
19 import android.widget.ListView;
20 import android.widget.Toast;
21
22 import com.fasterxml.jackson.databind.DeserializationFeature;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.readium.sample.R;
25
26 import org.readium.r2_streamer.model.container.Container;
27 import org.readium.r2_streamer.model.container.EpubContainer;
28 import org.readium.r2_streamer.model.publication.EpubPublication;
29 import org.readium.r2_streamer.model.publication.link.Link;
30 import org.readium.r2_streamer.model.searcher.SearchQueryResults;
31 import org.readium.r2_streamer.model.searcher.SearchResult;
32 import org.readium.r2_streamer.server.EpubServer;
33 import org.readium.r2_streamer.server.EpubServerSingleton;
34 import org.readium.sample.adapters.SearchListAdapter;
35 import org.readium.sample.adapters.SpineListAdapter;
36
37 import java.io.BufferedReader;
38 import java.io.File;
39 import java.io.FileOutputStream;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.InputStreamReader;
43 import java.net.HttpURLConnection;
44 import java.net.URL;
45 import java.net.URLConnection;
46 import java.util.ArrayList;
47 import java.util.List;
48
49 public class TestActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
50     private static final String ROOT_EPUB_PATH = Environment.getExternalStorageDirectory().getPath() + "/R2StreamerSample/";
51     private static final int WRITE_EXST = 100;
52     private final String TAG = "TestActivity";
53     private EpubServer mEpubServer;
54
55     private EditText searchBar;
56     private ListView listView;
57     private List<Link> manifestItemList = new ArrayList<>();
58     private List<SearchResult> searchList = new ArrayList<>();
59     private ProgressDialog progressDialog;
60
61     @Override
62     protected void onCreate(Bundle savedInstanceState) {
63         super.onCreate(savedInstanceState);
64
65         progressDialog = new ProgressDialog(this);
66         progressDialog.setMessage("Loading.... ");
67         progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
68         progressDialog.setIndeterminate(true);
69         progressDialog.setCancelable(false);
70         progressDialog.setCanceledOnTouchOutside(false);
71
72         askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_EXST);
73         setContentView(R.layout.activity_sample_main);
74         searchBar = (EditText) findViewById(R.id.searchField);
75         listView = (ListView) findViewById(R.id.list);
76
77         copyEpubFromAssetsToSdCard(Constant.EPUB_TITLE);
78         startServer();
79
80         Log.d(TAG, "Server is running. Point your browser at " + Constant.URL);
81     }
82
83     private void startServer() {
84         try {
85             mEpubServer = EpubServerSingleton.getEpubServerInstance(Constant.PORT_NUMBER);
86             mEpubServer.start();
87         } catch (IOException e) {
88             Log.e(TAG, "startServer IOException " + e.toString());
89         }
90     }
91
92     public void find(View view) throws IOException {
93         addEpub();
94         searchList.clear();
95         String searchQuery = searchBar.getText().toString();
96         if (!searchQuery.isEmpty()) {
97             progressDialog.show();
98             if (searchQuery.contains(" ")) {
99                 searchQuery = searchQuery.replaceAll(" ", "%20");
100             }
101             if (searchQuery.length() != 0) {
102                 String urlString = Constant.URL + "/search?query=" + searchQuery;
103                 new SearchListTask().execute(urlString);
104             }
105         } else {
106             searchBar.requestFocus();
107             searchBar.setError("Enter search query");
108         }
109     }
110
111     private void addEpub() throws IOException {
112         String path = ROOT_EPUB_PATH + Constant.EPUB_TITLE;
113         //DirectoryContainer directoryContainer = new DirectoryContainer(path);
114         Container epubContainer = new EpubContainer(path);
115         mEpubServer.addEpub(epubContainer, "/" + Constant.EPUB_TITLE);
116     }
117
118     public void show(View view) throws IOException {
119         progressDialog.show();
120         addEpub();
121         manifestItemList.clear();
122         String urlString = Constant.URL + Constant.MANIFEST;
123         Log.i(TAG, "urlString: " + urlString);
124         new SpineListTask().execute(urlString);
125     }
126
127     @Override
128     protected void onDestroy() {
129         super.onDestroy();
130         if (mEpubServer != null && mEpubServer.isAlive()) {
131             mEpubServer.stop();
132             EpubServerSingleton.resetServerInstance();
133         }
134
135         Log.d(TAG, "Server has been stopped");
136     }
137
138     public void copyEpubFromAssetsToSdCard(String epubFileName) {
139         try {
140             File dir = new File(ROOT_EPUB_PATH);
141             if (!dir.exists()) dir.mkdirs();
142             File file = new File(dir, epubFileName);
143             file.createNewFile();
144
145             FileOutputStream fos = new FileOutputStream(file);
146             InputStream fis = getAssets().open(Constant.EPUB_TITLE);
147             byte[] b = new byte[1024];
148             int i;
149             while ((i = fis.read(b)) != -1) {
150                 fos.write(b, 0, i);
151             }
152             fos.flush();
153             fos.close();
154             fis.close();
155         } catch (IOException e) {
156             Log.e(TAG, "copyEpubFromAssetsToSdCard IOException " + e.toString());
157         }
158     }
159
160     @Override
161     public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
162         String urlString = Constant.URL + "/" + manifestItemList.get(position).getHref();
163         //String urlString = "http://127.0.0.1:8080/BARRETT_GUIDE.epub/" + searchList.get(position).getResource();
164         Uri uri = Uri.parse(urlString);
165         Intent intent = new Intent(Intent.ACTION_VIEW, uri);
166         startActivity(intent);
167     }
168
169     class SpineListTask extends AsyncTask<String, Void, EpubPublication> {
170         @Override
171         protected EpubPublication doInBackground(String... urls) {
172             String strUrl = urls[0];
173
174             try {
175                 URL url = new URL(strUrl);
176                 URLConnection urlConnection = url.openConnection();
177                 InputStream inputStream = urlConnection.getInputStream();
178                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
179                 StringBuilder stringBuilder = new StringBuilder();
180                 String line;
181                 while ((line = bufferedReader.readLine()) != null) {
182                     stringBuilder.append(line);
183                 }
184
185                 Log.d("TestActivity", "EpubPublication => " + stringBuilder.toString());
186
187                 ObjectMapper objectMapper = new ObjectMapper();
188                 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
189
190                 return objectMapper.readValue(stringBuilder.toString(), EpubPublication.class);
191             } catch (IOException e) {
192                 Log.e(TAG, "SpineListTask error " + e);
193             }
194             return null;
195         }
196
197         @Override
198         protected void onPostExecute(EpubPublication epubPublication) {
199             manifestItemList = epubPublication.spines;
200             SpineListAdapter arrayAdapter = new SpineListAdapter(TestActivity.this, manifestItemList);
201             listView.setAdapter(arrayAdapter);
202             listView.setOnItemClickListener(TestActivity.this);
203             cancel(true);
204             progressDialog.dismiss();
205         }
206     }
207
208     class SearchListTask extends AsyncTask<String, Void, SearchQueryResults> {
209
210         @Override
211         protected SearchQueryResults doInBackground(String... urls) {
212             String strUrl = urls[0];
213             try {
214                 URL url = new URL(strUrl);
215                 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
216                 urlConnection.setRequestMethod("GET");
217                 InputStream inputStream = urlConnection.getInputStream();
218                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
219                 StringBuilder stringBuilder = new StringBuilder();
220                 String line;
221                 while ((line = bufferedReader.readLine()) != null) {
222                     stringBuilder.append(line);
223                 }
224
225                 ObjectMapper objectMapper = new ObjectMapper();
226                 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
227                 return objectMapper.readValue(stringBuilder.toString(), SearchQueryResults.class);
228             } catch (IOException e) {
229                 Log.e(TAG, "SearchListTask IOException " + e.toString());
230             }
231             return null;
232         }
233
234         @Override
235         protected void onPostExecute(SearchQueryResults results) {
236             searchList = results.searchResultList;
237             SearchListAdapter adapter = new SearchListAdapter(TestActivity.this, searchList);
238             listView.setAdapter(adapter);
239             listView.setOnItemClickListener(TestActivity.this);
240             cancel(true);
241             progressDialog.dismiss();
242         }
243     }
244
245     private void askForPermission(String permission, Integer requestCode) {
246         if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
247             if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
248                 ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
249             } else {
250                 ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
251             }
252         }
253     }
254
255     @Override
256     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
257         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
258         if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
259             if (requestCode == WRITE_EXST) {
260                 Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
261             }
262         } else {
263             Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
264             finish();
265         }
266     }
267 }