Send history feature now exports full CSV dump
[zxing.git] / android / src / com / google / zxing / client / android / history / HistoryManager.java
1 /*
2  * Copyright (C) 2009 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.history;
18
19 import android.app.AlertDialog;
20 import android.content.ContentValues;
21 import android.content.DialogInterface;
22 import android.content.Intent;
23 import android.content.res.Resources;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.database.sqlite.SQLiteOpenHelper;
26 import android.database.Cursor;
27 import android.net.Uri;
28 import android.os.Message;
29
30 import java.text.DateFormat;
31 import java.util.Date;
32 import java.util.List;
33 import java.util.ArrayList;
34
35 import com.google.zxing.BarcodeFormat;
36 import com.google.zxing.client.android.Intents;
37 import com.google.zxing.client.android.R;
38 import com.google.zxing.client.android.CaptureActivity;
39 import com.google.zxing.Result;
40
41 /**
42  * <p>Manages functionality related to scan history.</p>
43  * 
44  * @author Sean Owen
45  */
46 public final class HistoryManager {
47
48   private static final int MAX_ITEMS = 50;
49   private static final String[] TEXT_COL_PROJECTION = { DBHelper.TEXT_COL };
50   private static final String[] TEXT_FORMAT_COL_PROJECTION = { DBHelper.TEXT_COL, DBHelper.FORMAT_COL };
51   private static final String[] EXPORT_COL_PROJECTION = {
52       DBHelper.TEXT_COL,
53       DBHelper.DISPLAY_COL,
54       DBHelper.FORMAT_COL,
55       DBHelper.TIMESTAMP_COL,
56   };
57   private static final String[] ID_COL_PROJECTION = { DBHelper.ID_COL };
58   private static final DateFormat EXPORT_DATE_TIME_FORMAT = DateFormat.getDateTimeInstance();
59
60   private final CaptureActivity activity;
61
62   public HistoryManager(CaptureActivity activity) {
63     this.activity = activity;
64   }
65
66   List<Result> getHistoryItems() {
67     SQLiteOpenHelper helper = new DBHelper(activity);
68     List<Result> items = new ArrayList<Result>();
69     SQLiteDatabase db = helper.getReadableDatabase();
70     Cursor cursor = null;
71     try {
72       cursor = db.query(DBHelper.TABLE_NAME,
73                         TEXT_FORMAT_COL_PROJECTION,
74                         null, null, null, null,
75                         DBHelper.TIMESTAMP_COL + " DESC");
76       while (cursor.moveToNext()) {
77         Result result = new Result(cursor.getString(0), null, null, BarcodeFormat.valueOf(cursor.getString(1)));
78         items.add(result);
79       }
80     } finally {
81       if (cursor != null) {
82         cursor.close();
83       }
84       db.close();
85     }
86     return items;
87   }
88
89   public AlertDialog buildAlert() {
90     final List<Result> items = getHistoryItems();
91     final String[] dialogItems = new String[items.size() + 2];
92     for (int i = 0; i < items.size(); i++) {
93       dialogItems[i] = items.get(i).getText();
94     }
95     final Resources res = activity.getResources();
96     dialogItems[dialogItems.length - 2] = res.getString(R.string.history_send);
97     dialogItems[dialogItems.length - 1] = res.getString(R.string.history_clear_text);
98     DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
99       public void onClick(DialogInterface dialogInterface, int i) {
100         if (i == dialogItems.length - 1) {
101           clearHistory();
102         } else if (i == dialogItems.length - 2) {
103           CharSequence history = buildHistory();
104           Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
105           intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);          
106           intent.putExtra(Intent.EXTRA_SUBJECT, res.getString(R.string.history_email_title));
107           intent.putExtra(Intent.EXTRA_TEXT, history);
108           intent.setType("text/csv");
109           activity.startActivity(intent);
110         } else {
111           Result result = items.get(i);
112           Message message = Message.obtain(activity.getHandler(), R.id.decode_succeeded, result);
113           message.sendToTarget();
114         }
115       }
116     };
117     AlertDialog.Builder builder = new AlertDialog.Builder(activity);
118     builder.setTitle(R.string.history_title);
119     builder.setItems(dialogItems, clickListener);
120     return builder.create();
121   }
122
123   public void addHistoryItem(Result result) {
124
125     if (!activity.getIntent().getBooleanExtra(Intents.Scan.SAVE_HISTORY, true)) {
126       return; // Do not save this item to the history.
127     }
128
129     SQLiteOpenHelper helper = new DBHelper(activity);
130     SQLiteDatabase db = helper.getWritableDatabase();
131     Cursor cursor = null;
132     try {
133       cursor = db.query(DBHelper.TABLE_NAME,
134                         TEXT_COL_PROJECTION,
135                         DBHelper.TEXT_COL + "=?",
136                         new String[] { result.getText() },
137                         null, null, null, null);
138       if (cursor.moveToNext()) {
139         return;
140       }
141       ContentValues values = new ContentValues();
142       values.put(DBHelper.TEXT_COL, result.getText());
143       values.put(DBHelper.FORMAT_COL, result.getBarcodeFormat().toString());
144       values.put(DBHelper.DISPLAY_COL, result.getText()); // TODO use parsed result display value?
145       values.put(DBHelper.TIMESTAMP_COL, System.currentTimeMillis());
146       db.insert(DBHelper.TABLE_NAME, DBHelper.TIMESTAMP_COL, values);
147     } finally {
148       if (cursor != null) {
149         cursor.close();
150       }
151       db.close();
152     }
153   }
154
155   public void trimHistory() {
156     SQLiteOpenHelper helper = new DBHelper(activity);
157     SQLiteDatabase db = helper.getWritableDatabase();
158     Cursor cursor = null;
159     try {
160       cursor = db.query(DBHelper.TABLE_NAME,
161                         ID_COL_PROJECTION,
162                         null, null, null, null,
163                         DBHelper.TIMESTAMP_COL + " DESC");
164       int count = 0;
165       while (count < MAX_ITEMS && cursor.moveToNext()) {
166         count++;
167       }
168       while (cursor.moveToNext()) {
169         db.delete(DBHelper.TABLE_NAME, DBHelper.ID_COL + '=' + cursor.getString(0), null);
170       }
171     } finally {
172       if (cursor != null) {
173         cursor.close();
174       }
175       db.close();
176     }
177   }
178
179   /**
180    * <p>Builds a text representation of the scanning history. Each scan is encoded on one
181    * line, terminated by a line break (\n). The values in each line are comma-separated,
182    * and double-quoted. Double-quotes within values are escaped with a sequence of two
183    * double-quotes. The fields output are:</p>
184    *
185    * <ul>
186    *  <li>Raw text</li>
187    *  <li>Display text</li>
188    *  <li>Format (e.g. QR_CODE)</li>
189    *  <li>Timestamp</li>
190    *  <li>Formatted version of timestamp</li>
191    * </ul>
192    */
193   private CharSequence buildHistory() {
194     StringBuilder historyText = new StringBuilder(1000);
195     SQLiteOpenHelper helper = new DBHelper(activity);
196     SQLiteDatabase db = helper.getReadableDatabase();
197     Cursor cursor = null;
198     try {
199       cursor = db.query(DBHelper.TABLE_NAME,
200                         EXPORT_COL_PROJECTION,
201                         null, null, null, null,
202                         DBHelper.TIMESTAMP_COL + " DESC");
203       while (cursor.moveToNext()) {
204         for (int col = 0; col < EXPORT_COL_PROJECTION.length; col++) {
205           historyText.append('"').append(massageHistoryField(cursor.getString(col)));
206         }
207         // Add timestamp again, formatted
208         long timestamp = cursor.getLong(EXPORT_COL_PROJECTION.length - 1);
209         historyText.append('"').append(massageHistoryField(EXPORT_DATE_TIME_FORMAT.format(new Date(timestamp))))
210             .append('"').append('\n');
211       }
212     } finally {
213       if (cursor != null) {
214         cursor.close();
215       }
216       db.close();
217     }
218     return historyText;
219   }
220
221   private static String massageHistoryField(String value) {
222     return value.replace("\"","\"\"");
223   }
224
225   void clearHistory() {
226     SQLiteOpenHelper helper = new DBHelper(activity);
227     SQLiteDatabase db = helper.getWritableDatabase();
228     try {
229       db.delete(DBHelper.TABLE_NAME, null, null);
230     } finally {
231       db.close();
232     }
233   }
234
235 }