Committing Jeff's latest for ISSUE-238. May still be an issue with international...
[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
63   private static final String TAG = "SearchBookContents";
64   private static final String USER_AGENT = "ZXing (Android)";
65   private static final Pattern TAG_PATTERN = Pattern.compile("\\<.*?\\>");
66   private static final Pattern LT_ENTITY_PATTERN = Pattern.compile("&lt;");
67   private static final Pattern GT_ENTITY_PATTERN = Pattern.compile("&gt;");
68   private static final Pattern QUOTE_ENTITY_PATTERN = Pattern.compile("&#39;");
69   private static final Pattern QUOT_ENTITY_PATTERN = Pattern.compile("&quot;");
70
71   private NetworkThread networkThread;
72   private String isbn;
73   private EditText queryTextView;
74   private Button queryButton;
75   private ListView resultListView;
76   private TextView headerView;
77
78   private final Handler handler = new Handler() {
79     @Override
80     public void handleMessage(Message message) {
81       switch (message.what) {
82         case R.id.search_book_contents_succeeded:
83           handleSearchResults((JSONObject) message.obj);
84           resetForNewQuery();
85           break;
86         case R.id.search_book_contents_failed:
87           resetForNewQuery();
88           headerView.setText(R.string.msg_sbc_failed);
89           break;
90       }
91     }
92   };
93
94   private final Button.OnClickListener buttonListener = new Button.OnClickListener() {
95     public void onClick(View view) {
96       launchSearch();
97     }
98   };
99
100   private final View.OnKeyListener keyListener = new View.OnKeyListener() {
101     public boolean onKey(View view, int keyCode, KeyEvent event) {
102       if (keyCode == KeyEvent.KEYCODE_ENTER) {
103         launchSearch();
104         return true;
105       }
106       return false;
107     }
108   };
109
110   String getISBN() {
111     return isbn;
112   }
113
114   @Override
115   public void onCreate(Bundle icicle) {
116     super.onCreate(icicle);
117
118     // Make sure that expired cookies are removed on launch.
119     CookieSyncManager.createInstance(this);
120     CookieManager.getInstance().removeExpiredCookie();
121
122     Intent intent = getIntent();
123     if (intent == null || (!intent.getAction().equals(Intents.SearchBookContents.ACTION))) {
124       finish();
125       return;
126     }
127
128     isbn = intent.getStringExtra(Intents.SearchBookContents.ISBN);
129     if (isbn.startsWith("http://google.com/books?id=")) {
130       setTitle(getString(R.string.sbc_name));
131     } else {
132       setTitle(getString(R.string.sbc_name) + ": ISBN " + isbn);
133     }
134
135     setContentView(R.layout.search_book_contents);
136     queryTextView = (EditText) findViewById(R.id.query_text_view);
137
138     String initialQuery = intent.getStringExtra(Intents.SearchBookContents.QUERY);
139     if (initialQuery != null && initialQuery.length() > 0) {
140       // Populate the search box but don't trigger the search
141       queryTextView.setText(initialQuery);
142     }
143     queryTextView.setOnKeyListener(keyListener);
144
145     queryButton = (Button) findViewById(R.id.query_button);
146     queryButton.setOnClickListener(buttonListener);
147
148     resultListView = (ListView) findViewById(R.id.result_list_view);
149     LayoutInflater factory = LayoutInflater.from(this);
150     headerView = (TextView) factory.inflate(R.layout.search_book_contents_header,
151         resultListView, false);
152     resultListView.addHeaderView(headerView);
153   }
154
155   @Override
156   protected void onResume() {
157     super.onResume();
158     queryTextView.selectAll();
159   }
160
161   @Override
162   public void onConfigurationChanged(Configuration config) {
163     // Do nothing, this is to prevent the activity from being restarted when the keyboard opens.
164     super.onConfigurationChanged(config);
165   }
166
167   private void resetForNewQuery() {
168     networkThread = null;
169     queryTextView.setEnabled(true);
170     queryTextView.selectAll();
171     queryButton.setEnabled(true);
172   }
173
174   private void launchSearch() {
175     if (networkThread == null) {
176       String query = queryTextView.getText().toString();
177       if (query != null && query.length() > 0) {
178         networkThread = new NetworkThread(isbn, query, handler);
179         networkThread.start();
180         headerView.setText(R.string.msg_sbc_searching_book);
181         resultListView.setAdapter(null);
182         queryTextView.setEnabled(false);
183         queryButton.setEnabled(false);
184       }
185     }
186   }
187
188   // Currently there is no way to distinguish between a query which had no results and a book
189   // which is not searchable - both return zero results.
190   private void handleSearchResults(JSONObject json) {
191     try {
192       int count = json.getInt("number_of_results");
193       headerView.setText("Found " + (count == 1 ? "1 result" : count + " results"));
194       if (count > 0) {
195         JSONArray results = json.getJSONArray("search_results");
196         SearchBookContentsResult.setQuery(queryTextView.getText().toString());
197         List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(count);
198         for (int x = 0; x < count; x++) {
199           items.add(parseResult(results.getJSONObject(x)));
200         }
201               resultListView.setOnItemClickListener(new BrowseBookListener(this, items));
202         resultListView.setAdapter(new SearchBookContentsAdapter(this, items));
203       } else {
204         String searchable = json.optString("searchable");
205         if ("false".equals(searchable)) {
206           headerView.setText(R.string.msg_sbc_book_not_searchable);
207         }
208         resultListView.setAdapter(null);
209       }
210     } catch (JSONException e) {
211       Log.e(TAG, e.toString());
212       resultListView.setAdapter(null);
213       headerView.setText(R.string.msg_sbc_failed);
214     }
215   }
216
217   // Available fields: page_id, page_number, page_url, snippet_text
218   private SearchBookContentsResult parseResult(JSONObject json) {
219     try {
220       String pageId = json.getString("page_id");
221       String pageNumber = json.getString("page_number");
222       if (pageNumber.length() > 0) {
223         pageNumber = getString(R.string.msg_sbc_page) + ' ' + pageNumber;
224       } else {
225         // This can happen for text on the jacket, and possibly other reasons.
226         pageNumber = getString(R.string.msg_sbc_unknown_page);
227       }
228
229       // Remove all HTML tags and encoded characters. Ideally the server would do this.
230       String snippet = json.optString("snippet_text");
231       boolean valid = true;
232       if (snippet.length() > 0) {
233         snippet = TAG_PATTERN.matcher(snippet).replaceAll("");
234         snippet = LT_ENTITY_PATTERN.matcher(snippet).replaceAll("<");
235         snippet = GT_ENTITY_PATTERN.matcher(snippet).replaceAll(">");
236         snippet = QUOTE_ENTITY_PATTERN.matcher(snippet).replaceAll("'");
237         snippet = QUOT_ENTITY_PATTERN.matcher(snippet).replaceAll("\"");
238       } else {
239         snippet = '(' + getString(R.string.msg_sbc_snippet_unavailable) + ')';
240         valid = false;
241       }
242       return new SearchBookContentsResult(pageId, pageNumber, snippet, valid);
243     } catch (JSONException e) {
244       // Never seen in the wild, just being complete.
245             return new SearchBookContentsResult(getString(R.string.msg_sbc_no_page_returned), "", "", false);
246     }
247   }
248
249   private static final class NetworkThread extends Thread {
250     private final String isbn;
251     private final String query;
252     private final Handler handler;
253
254     NetworkThread(String isbn, String query, Handler handler) {
255       this.isbn = isbn;
256       this.query = query;
257       this.handler = handler;
258     }
259
260     @Override
261     public void run() {
262       AndroidHttpClient client = null;
263       try {
264         // These return a JSON result which describes if and where the query was found. This API may
265         // break or disappear at any time in the future. Since this is an API call rather than a
266         // website, we don't use LocaleManager to change the TLD.
267         URI uri;
268         if (isbn.startsWith("http://google.com/books?id=")) {
269                 int equals = isbn.indexOf('=');
270           String volumeId = isbn.substring(equals + 1);
271           uri = new URI("http", null, "www.google.com", -1, "/books", "id=" + volumeId +
272                         "&jscmd=SearchWithinVolume2&q=" + query, null);
273         } else {
274           uri = new URI("http", null, "www.google.com", -1, "/books", "vid=isbn" + isbn +
275                         "&jscmd=SearchWithinVolume2&q=" + query, null);
276         }
277         HttpUriRequest get = new HttpGet(uri);
278         get.setHeader("cookie", getCookie(uri.toString()));
279         client = AndroidHttpClient.newInstance(USER_AGENT);
280         HttpResponse response = client.execute(get);
281         if (response.getStatusLine().getStatusCode() == 200) {
282           HttpEntity entity = response.getEntity();
283           ByteArrayOutputStream jsonHolder = new ByteArrayOutputStream();
284           entity.writeTo(jsonHolder);
285           jsonHolder.flush();
286           JSONObject json = new JSONObject(jsonHolder.toString(getEncoding(entity)));
287           jsonHolder.close();
288
289           Message message = Message.obtain(handler, R.id.search_book_contents_succeeded);
290           message.obj = json;
291           message.sendToTarget();
292         } else {
293           Log.e(TAG, "HTTP returned " + response.getStatusLine().getStatusCode() + " for " + uri);
294           Message message = Message.obtain(handler, R.id.search_book_contents_failed);
295           message.sendToTarget();
296         }
297       } catch (Exception e) {
298         Log.e(TAG, e.toString());
299         Message message = Message.obtain(handler, R.id.search_book_contents_failed);
300         message.sendToTarget();
301       } finally {
302         if (client != null) {
303           client.close();
304         }
305       }
306     }
307
308     // Book Search requires a cookie to work, which we store persistently. If the cookie does
309     // not exist, this could be the first search or it has expired. Either way, do a quick HEAD
310     // request to fetch it, save it via the CookieSyncManager to flash, then return it.
311     private static String getCookie(String url) {
312       String cookie = CookieManager.getInstance().getCookie(url);
313       if (cookie == null || cookie.length() == 0) {
314         Log.v(TAG, "Book Search cookie was missing or expired");
315         HttpUriRequest head = new HttpHead(url);
316         AndroidHttpClient client = AndroidHttpClient.newInstance(USER_AGENT);
317         try {
318           HttpResponse response = client.execute(head);
319           if (response.getStatusLine().getStatusCode() == 200) {
320             Header[] cookies = response.getHeaders("set-cookie");
321             for (Header theCookie : cookies) {
322               CookieManager.getInstance().setCookie(url, theCookie.getValue());
323             }
324             CookieSyncManager.getInstance().sync();
325             cookie = CookieManager.getInstance().getCookie(url);
326           }
327         } catch (IOException e) {
328           Log.e(TAG, e.toString());
329         }
330         client.close();
331       }
332       return cookie;
333     }
334
335     private static String getEncoding(HttpEntity entity) {
336       // FIXME: The server is returning ISO-8859-1 but the content is actually windows-1252.
337       // Once Jeff fixes the HTTP response, remove this hardcoded value and go back to getting
338       // the encoding dynamically.
339       return "windows-1252";
340 //            HeaderElement[] elements = entity.getContentType().getElements();
341 //            if (elements != null && elements.length > 0) {
342 //                String encoding = elements[0].getParameterByName("charset").getValue();
343 //                if (encoding != null && encoding.length() > 0) {
344 //                    return encoding;
345 //                }
346 //            }
347 //            return "UTF-8";
348     }
349   }
350 }