Add history feature; group some functionality into subpackages
[zxing.git] / android / src / com / google / zxing / client / android / book / SearchBookContentsActivity.java
1 /*
2  * Copyright (C) 2008 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.android.book;
18
19 import android.app.Activity;
20 import android.content.Intent;
21 import android.content.res.Configuration;
22 import android.os.Bundle;
23 import android.os.Handler;
24 import android.os.Message;
25 import android.util.Log;
26 import android.view.KeyEvent;
27 import android.view.LayoutInflater;
28 import android.view.View;
29 import android.webkit.CookieManager;
30 import android.webkit.CookieSyncManager;
31 import android.widget.Button;
32 import android.widget.EditText;
33 import android.widget.ListView;
34 import android.widget.TextView;
35 import org.apache.http.Header;
36 import org.apache.http.HttpEntity;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.client.methods.HttpGet;
39 import org.apache.http.client.methods.HttpHead;
40 import org.apache.http.client.methods.HttpUriRequest;
41 import org.json.JSONArray;
42 import org.json.JSONException;
43 import org.json.JSONObject;
44
45 import java.io.ByteArrayOutputStream;
46 import java.io.IOException;
47 import java.net.URI;
48 import java.util.ArrayList;
49 import java.util.List;
50 import java.util.regex.Pattern;
51
52 import com.google.zxing.client.android.R;
53 import com.google.zxing.client.android.Intents;
54 import com.google.zxing.client.android.AndroidHttpClient;
55
56 /**
57  * Uses Google Book Search to find a word or phrase in the requested book.
58  *
59  * @author dswitkin@google.com (Daniel Switkin)
60  */
61 public final class SearchBookContentsActivity extends Activity {
62   private static final String TAG = "SearchBookContents";
63   private static final String USER_AGENT = "ZXing (Android)";
64
65   private NetworkThread networkThread;
66   private String isbn;
67   private EditText queryTextView;
68   private Button queryButton;
69   private ListView resultListView;
70   private TextView headerView;
71
72   private final Handler handler = new Handler() {
73     @Override
74     public void handleMessage(Message message) {
75       switch (message.what) {
76         case R.id.search_book_contents_succeeded:
77           handleSearchResults((JSONObject) message.obj);
78           resetForNewQuery();
79           break;
80         case R.id.search_book_contents_failed:
81           resetForNewQuery();
82           headerView.setText(R.string.msg_sbc_failed);
83           break;
84       }
85     }
86   };
87
88   private final Button.OnClickListener buttonListener = new Button.OnClickListener() {
89     public void onClick(View view) {
90       launchSearch();
91     }
92   };
93
94   private final View.OnKeyListener keyListener = new View.OnKeyListener() {
95     public boolean onKey(View view, int keyCode, KeyEvent event) {
96       if (keyCode == KeyEvent.KEYCODE_ENTER) {
97         launchSearch();
98         return true;
99       }
100       return false;
101     }
102   };
103   private static final Pattern TAG_PATTERN = Pattern.compile("\\<.*?\\>");
104   private static final Pattern LT_ENTITY_PATTERN = Pattern.compile("&lt;");
105   private static final Pattern GT_ENTITY_PATTERN = Pattern.compile("&gt;");
106   private static final Pattern QUOTE_ENTITY_PATTERN = Pattern.compile("&#39;");
107   private static final Pattern QUOT_ENTITY_PATTERN = Pattern.compile("&quot;");
108
109   @Override
110   public void onCreate(Bundle icicle) {
111     super.onCreate(icicle);
112
113     // Make sure that expired cookies are removed on launch.
114     CookieSyncManager.createInstance(this);
115     CookieManager.getInstance().removeExpiredCookie();
116
117     Intent intent = getIntent();
118     if (intent == null || (!intent.getAction().equals(Intents.SearchBookContents.ACTION))) {
119       finish();
120       return;
121     }
122
123     isbn = intent.getStringExtra(Intents.SearchBookContents.ISBN);
124     setTitle(getString(R.string.sbc_name) + ": ISBN " + isbn);
125
126     setContentView(R.layout.search_book_contents);
127     queryTextView = (EditText) findViewById(R.id.query_text_view);
128
129     String initialQuery = intent.getStringExtra(Intents.SearchBookContents.QUERY);
130     if (initialQuery != null && initialQuery.length() > 0) {
131       // Populate the search box but don't trigger the search
132       queryTextView.setText(initialQuery);
133     }
134     queryTextView.setOnKeyListener(keyListener);
135
136     queryButton = (Button) findViewById(R.id.query_button);
137     queryButton.setOnClickListener(buttonListener);
138
139     resultListView = (ListView) findViewById(R.id.result_list_view);
140     LayoutInflater factory = LayoutInflater.from(this);
141     headerView = (TextView) factory.inflate(R.layout.search_book_contents_header,
142         resultListView, false);
143     resultListView.addHeaderView(headerView);
144   }
145
146   @Override
147   protected void onResume() {
148     super.onResume();
149     queryTextView.selectAll();
150   }
151
152   @Override
153   public void onConfigurationChanged(Configuration config) {
154     // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
155     super.onConfigurationChanged(config);
156   }
157
158   private void resetForNewQuery() {
159     networkThread = null;
160     queryTextView.setEnabled(true);
161     queryTextView.selectAll();
162     queryButton.setEnabled(true);
163   }
164
165   private void launchSearch() {
166     if (networkThread == null) {
167       String query = queryTextView.getText().toString();
168       if (query != null && query.length() > 0) {
169         networkThread = new NetworkThread(isbn, query, handler);
170         networkThread.start();
171         headerView.setText(R.string.msg_sbc_searching_book);
172         resultListView.setAdapter(null);
173         queryTextView.setEnabled(false);
174         queryButton.setEnabled(false);
175       }
176     }
177   }
178
179   // Currently there is no way to distinguish between a query which had no results and a book
180   // which is not searchable - both return zero results.
181   private void handleSearchResults(JSONObject json) {
182     try {
183       int count = json.getInt("number_of_results");
184       headerView.setText("Found " + (count == 1 ? "1 result" : count + " results"));
185       if (count > 0) {
186         JSONArray results = json.getJSONArray("search_results");
187         SearchBookContentsResult.setQuery(queryTextView.getText().toString());
188         List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(count);
189         for (int x = 0; x < count; x++) {
190           items.add(parseResult(results.getJSONObject(x)));
191         }
192         resultListView.setAdapter(new SearchBookContentsAdapter(this, items));
193       } else {
194         String searchable = json.optString("searchable");
195         if ("false".equals(searchable)) {
196           headerView.setText(R.string.msg_sbc_book_not_searchable);
197         }
198         resultListView.setAdapter(null);
199       }
200     } catch (JSONException e) {
201       Log.e(TAG, e.toString());
202       resultListView.setAdapter(null);
203       headerView.setText(R.string.msg_sbc_failed);
204     }
205   }
206
207   // Available fields: page_number, page_id, page_url, snippet_text
208   private SearchBookContentsResult parseResult(JSONObject json) {
209     try {
210       String pageNumber = json.getString("page_number");
211       if (pageNumber.length() > 0) {
212         pageNumber = getString(R.string.msg_sbc_page) + ' ' + pageNumber;
213       } else {
214         // This can happen for text on the jacket, and possibly other reasons.
215         pageNumber = getString(R.string.msg_sbc_unknown_page);
216       }
217
218       // Remove all HTML tags and encoded characters. Ideally the server would do this.
219       String snippet = json.optString("snippet_text");
220       boolean valid = true;
221       if (snippet.length() > 0) {
222         snippet = TAG_PATTERN.matcher(snippet).replaceAll("");
223         snippet = LT_ENTITY_PATTERN.matcher(snippet).replaceAll("<");
224         snippet = GT_ENTITY_PATTERN.matcher(snippet).replaceAll(">");
225         snippet = QUOTE_ENTITY_PATTERN.matcher(snippet).replaceAll("'");
226         snippet = QUOT_ENTITY_PATTERN.matcher(snippet).replaceAll("\"");
227       } else {
228         snippet = '(' + getString(R.string.msg_sbc_snippet_unavailable) + ')';
229         valid = false;
230       }
231       return new SearchBookContentsResult(pageNumber, snippet, valid);
232     } catch (JSONException e) {
233       // Never seen in the wild, just being complete.
234       return new SearchBookContentsResult(getString(R.string.msg_sbc_no_page_returned), "", false);
235     }
236   }
237
238   private static final class NetworkThread extends Thread {
239     private final String isbn;
240     private final String query;
241     private final Handler handler;
242
243     NetworkThread(String isbn, String query, Handler handler) {
244       this.isbn = isbn;
245       this.query = query;
246       this.handler = handler;
247     }
248
249     @Override
250     public void run() {
251       AndroidHttpClient client = null;
252       try {
253         // These return a JSON result which describes if and where the query was found. This API may
254         // break or disappear at any time in the future. Since this is an API call rather than a
255         // website, we don't use LocaleManager to change the TLD.
256         URI uri = new URI("http", null, "www.google.com", -1, "/books", "vid=isbn" + isbn +
257             "&jscmd=SearchWithinVolume2&q=" + query, null);
258         HttpUriRequest get = new HttpGet(uri);
259         get.setHeader("cookie", getCookie(uri.toString()));
260         client = AndroidHttpClient.newInstance(USER_AGENT);
261         HttpResponse response = client.execute(get);
262         if (response.getStatusLine().getStatusCode() == 200) {
263           HttpEntity entity = response.getEntity();
264           ByteArrayOutputStream jsonHolder = new ByteArrayOutputStream();
265           entity.writeTo(jsonHolder);
266           jsonHolder.flush();
267           JSONObject json = new JSONObject(jsonHolder.toString(getEncoding(entity)));
268           jsonHolder.close();
269
270           Message message = Message.obtain(handler, R.id.search_book_contents_succeeded);
271           message.obj = json;
272           message.sendToTarget();
273         } else {
274           Log.e(TAG, "HTTP returned " + response.getStatusLine().getStatusCode() + " for " + uri);
275           Message message = Message.obtain(handler, R.id.search_book_contents_failed);
276           message.sendToTarget();
277         }
278       } catch (Exception e) {
279         Log.e(TAG, e.toString());
280         Message message = Message.obtain(handler, R.id.search_book_contents_failed);
281         message.sendToTarget();
282       } finally {
283         if (client != null) {
284           client.close();
285         }
286       }
287     }
288
289     // Book Search requires a cookie to work, which we store persistently. If the cookie does
290     // not exist, this could be the first search or it has expired. Either way, do a quick HEAD
291     // request to fetch it, save it via the CookieSyncManager to flash, then return it.
292     private static String getCookie(String url) {
293       String cookie = CookieManager.getInstance().getCookie(url);
294       if (cookie == null || cookie.length() == 0) {
295         Log.v(TAG, "Book Search cookie was missing or expired");
296         HttpUriRequest head = new HttpHead(url);
297         AndroidHttpClient client = AndroidHttpClient.newInstance(USER_AGENT);
298         try {
299           HttpResponse response = client.execute(head);
300           if (response.getStatusLine().getStatusCode() == 200) {
301             Header[] cookies = response.getHeaders("set-cookie");
302             for (Header theCookie : cookies) {
303               CookieManager.getInstance().setCookie(url, theCookie.getValue());
304             }
305             CookieSyncManager.getInstance().sync();
306             cookie = CookieManager.getInstance().getCookie(url);
307           }
308         } catch (IOException e) {
309           Log.e(TAG, e.toString());
310         }
311         client.close();
312       }
313       return cookie;
314     }
315
316     private static String getEncoding(HttpEntity entity) {
317       // FIXME: The server is returning ISO-8859-1 but the content is actually windows-1252.
318       // Once Jeff fixes the HTTP response, remove this hardcoded value and go back to getting
319       // the encoding dynamically.
320       return "windows-1252";
321 //            HeaderElement[] elements = entity.getContentType().getElements();
322 //            if (elements != null && elements.length > 0) {
323 //                String encoding = elements[0].getParameterByName("charset").getValue();
324 //                if (encoding != null && encoding.length() > 0) {
325 //                    return encoding;
326 //                }
327 //            }
328 //            return "UTF-8";
329     }
330   }
331 }