Fixed crashed when the user tries to upload to ownCloud some content for wich the...
[pub/Android/ownCloud.git] / src / com / owncloud / android / Uploader.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package com.owncloud.android;
19
20 import java.io.File;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Stack;
26 import java.util.Vector;
27
28 import com.owncloud.android.authenticator.AccountAuthenticator;
29 import com.owncloud.android.datamodel.DataStorageManager;
30 import com.owncloud.android.datamodel.FileDataStorageManager;
31 import com.owncloud.android.datamodel.OCFile;
32 import com.owncloud.android.files.services.FileUploader;
33
34 import android.accounts.Account;
35 import android.accounts.AccountManager;
36 import android.app.AlertDialog;
37 import android.app.AlertDialog.Builder;
38 import android.app.Dialog;
39 import android.app.ListActivity;
40 import android.app.ProgressDialog;
41 import android.content.Context;
42 import android.content.DialogInterface;
43 import android.content.DialogInterface.OnCancelListener;
44 import android.content.DialogInterface.OnClickListener;
45 import android.content.Intent;
46 import android.database.Cursor;
47 import android.net.Uri;
48 import android.os.Bundle;
49 import android.os.Parcelable;
50 import android.provider.MediaStore.Images.Media;
51 import android.util.Log;
52 import android.view.View;
53 import android.view.Window;
54 import android.widget.AdapterView;
55 import android.widget.AdapterView.OnItemClickListener;
56 import android.widget.Button;
57 import android.widget.EditText;
58 import android.widget.SimpleAdapter;
59 import android.widget.Toast;
60
61 import com.owncloud.android.R;
62 import eu.alefzero.webdav.WebdavClient;
63
64 /**
65 * This can be used to upload things to an ownCloud instance.
66 *
67 * @author Bartek Przybylski
68 *
69 */
70 public class Uploader extends ListActivity implements OnItemClickListener, android.view.View.OnClickListener {
71 private static final String TAG = "ownCloudUploader";
72
73 private Account mAccount;
74 private AccountManager mAccountManager;
75 private Stack<String> mParents;
76 private ArrayList<Parcelable> mStreamsToUpload;
77 private boolean mCreateDir;
78 private String mUploadPath;
79 private static final String[] CONTENT_PROJECTION = { Media.DATA, Media.DISPLAY_NAME, Media.MIME_TYPE, Media.SIZE };
80 private DataStorageManager mStorageManager;
81 private OCFile mFile;
82
83 private final static int DIALOG_NO_ACCOUNT = 0;
84 private final static int DIALOG_WAITING = 1;
85 private final static int DIALOG_NO_STREAM = 2;
86 private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
87 private final static int DIALOG_GET_DIRNAME = 4;
88
89 private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
90
91 @Override
92 protected void onCreate(Bundle savedInstanceState) {
93 super.onCreate(savedInstanceState);
94 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
95 mParents = new Stack<String>();
96 mParents.add("");
97 if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
98 prepareStreamsToUpload();
99 mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
100 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
101 if (accounts.length == 0) {
102 Log.i(TAG, "No ownCloud account is available");
103 showDialog(DIALOG_NO_ACCOUNT);
104 } else if (accounts.length > 1) {
105 Log.i(TAG, "More then one ownCloud is available");
106 showDialog(DIALOG_MULTIPLE_ACCOUNT);
107 } else {
108 mAccount = accounts[0];
109 setContentView(R.layout.uploader_layout);
110 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
111 populateDirectoryList();
112 }
113 } else {
114 showDialog(DIALOG_NO_STREAM);
115 }
116 }
117
118 @Override
119 protected Dialog onCreateDialog(final int id) {
120 final AlertDialog.Builder builder = new Builder(this);
121 switch (id) {
122 case DIALOG_WAITING:
123 ProgressDialog pDialog = new ProgressDialog(this);
124 pDialog.setIndeterminate(false);
125 pDialog.setCancelable(false);
126 pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));
127 return pDialog;
128 case DIALOG_NO_ACCOUNT:
129 builder.setIcon(android.R.drawable.ic_dialog_alert);
130 builder.setTitle(R.string.uploader_wrn_no_account_title);
131 builder.setMessage(R.string.uploader_wrn_no_account_text);
132 builder.setCancelable(false);
133 builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
134 public void onClick(DialogInterface dialog, int which) {
135 if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
136 // using string value since in API7 this
137 // constatn is not defined
138 // in API7 < this constatant is defined in
139 // Settings.ADD_ACCOUNT_SETTINGS
140 // and Settings.EXTRA_AUTHORITIES
141 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
142 intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
143 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
144 } else {
145 // since in API7 there is no direct call for
146 // account setup, so we need to
147 // show our own AccountSetupAcricity, get
148 // desired results and setup
149 // everything for ourself
150 Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
151 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
152 }
153 }
154 });
155 builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
156 public void onClick(DialogInterface dialog, int which) {
157 finish();
158 }
159 });
160 return builder.create();
161 /*case DIALOG_GET_DIRNAME:
162 final EditText dirName = new EditText(getBaseContext());
163 builder.setView(dirName);
164 builder.setTitle(R.string.uploader_info_dirname);
165 String pathToUpload;
166 if (mParents.empty()) {
167 pathToUpload = "/";
168 } else {
169 mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), null,
170 null, null, null);
171 mCursor.moveToFirst();
172 pathToUpload = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH))
173 + mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_NAME)).replace(" ", "%20"); // TODO don't make this ; use WebdavUtils.encode in the right moment
174 }
175 a a = new a(pathToUpload, dirName);
176 builder.setPositiveButton(R.string.common_ok, a);
177 builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
178 public void onClick(DialogInterface dialog, int which) {
179 dialog.cancel();
180 }
181 });
182 return builder.create();*/
183 case DIALOG_MULTIPLE_ACCOUNT:
184 CharSequence ac[] = new CharSequence[mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE).length];
185 for (int i = 0; i < ac.length; ++i) {
186 ac[i] = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[i].name;
187 }
188 builder.setTitle(R.string.common_choose_account);
189 builder.setItems(ac, new OnClickListener() {
190 public void onClick(DialogInterface dialog, int which) {
191 mAccount = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];
192 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
193 populateDirectoryList();
194 }
195 });
196 builder.setCancelable(true);
197 builder.setOnCancelListener(new OnCancelListener() {
198 public void onCancel(DialogInterface dialog) {
199 dialog.cancel();
200 finish();
201 }
202 });
203 return builder.create();
204 default:
205 throw new IllegalArgumentException("Unknown dialog id: " + id);
206 }
207 }
208
209 class a implements OnClickListener {
210 String mPath;
211 EditText mDirname;
212
213 public a(String path, EditText dirname) {
214 mPath = path;
215 mDirname = dirname;
216 }
217
218 public void onClick(DialogInterface dialog, int which) {
219 Uploader.this.mUploadPath = mPath + mDirname.getText().toString();
220 Uploader.this.mCreateDir = true;
221 uploadFiles();
222 }
223 }
224
225 @Override
226 public void onBackPressed() {
227
228 if (mParents.size() <= 1) {
229 super.onBackPressed();
230 return;
231 } else {
232 mParents.pop();
233 populateDirectoryList();
234 }
235 }
236
237 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
238 // click on folder in the list
239 Log.d(TAG, "on item click");
240 Vector<OCFile> tmpfiles = mStorageManager.getDirectoryContent(mFile);
241 if (tmpfiles == null) return;
242 // filter on dirtype
243 Vector<OCFile> files = new Vector<OCFile>();
244 for (OCFile f : tmpfiles)
245 if (f.isDirectory())
246 files.add(f);
247 if (files.size() < position) {
248 throw new IndexOutOfBoundsException("Incorrect item selected");
249 }
250 mParents.push(files.get(position).getFileName());
251 populateDirectoryList();
252 }
253
254 public void onClick(View v) {
255 // click on button
256 switch (v.getId()) {
257 case R.id.uploader_choose_folder:
258 mUploadPath = ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
259 for (String p : mParents)
260 mUploadPath += p + OCFile.PATH_SEPARATOR;
261 Log.d(TAG, "Uploading file to dir " + mUploadPath);
262
263 uploadFiles();
264
265 break;
266 case android.R.id.button1: // dynamic action for create aditional dir
267 showDialog(DIALOG_GET_DIRNAME);
268 break;
269 default:
270 throw new IllegalArgumentException("Wrong element clicked");
271 }
272 }
273
274 @Override
275 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
276 super.onActivityResult(requestCode, resultCode, data);
277 Log.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
278 if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
279 dismissDialog(DIALOG_NO_ACCOUNT);
280 if (resultCode == RESULT_CANCELED) {
281 finish();
282 }
283 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);
284 if (accounts.length == 0) {
285 showDialog(DIALOG_NO_ACCOUNT);
286 } else {
287 // there is no need for checking for is there more then one
288 // account at this point
289 // since account setup can set only one account at time
290 mAccount = accounts[0];
291 populateDirectoryList();
292 }
293 }
294 }
295
296 private void populateDirectoryList() {
297 setContentView(R.layout.uploader_layout);
298
299 String full_path = "";
300 for (String a : mParents)
301 full_path += a + "/";
302
303 Log.d(TAG, "Populating view with content of : " + full_path);
304
305 mFile = mStorageManager.getFileByPath(full_path);
306 if (mFile != null) {
307 Vector<OCFile> files = mStorageManager.getDirectoryContent(mFile);
308 if (files != null) {
309 List<HashMap<String, Object>> data = new LinkedList<HashMap<String,Object>>();
310 for (OCFile f : files) {
311 HashMap<String, Object> h = new HashMap<String, Object>();
312 if (f.isDirectory()) {
313 h.put("dirname", f.getFileName());
314 data.add(h);
315 }
316 }
317 SimpleAdapter sa = new SimpleAdapter(this,
318 data,
319 R.layout.uploader_list_item_layout,
320 new String[] {"dirname"},
321 new int[] {R.id.textView1});
322 setListAdapter(sa);
323 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
324 btn.setOnClickListener(this);
325 getListView().setOnItemClickListener(this);
326 }
327 }
328 /*
329 mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI, null, ProviderTableMeta.FILE_NAME
330 + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { "/", mAccount.name }, null);
331
332 if (mCursor.moveToFirst()) {
333 mCursor = managedQuery(
334 ProviderMeta.ProviderTableMeta.CONTENT_URI,
335 null,
336 ProviderTableMeta.FILE_CONTENT_TYPE + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND "
337 + ProviderTableMeta.FILE_PARENT + "=?",
338 new String[] { "DIR", mAccount.name,
339 mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta._ID)) }, null);
340
341 ListView lv = getListView();
342 lv.setOnItemClickListener(this);
343 SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.uploader_list_item_layout, mCursor,
344 new String[] { ProviderTableMeta.FILE_NAME }, new int[] { R.id.textView1 });
345 setListAdapter(sca);
346 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
347 btn.setOnClickListener(this);
348 /*
349 * disable this until new server interaction service wont be created
350 * // insert create new directory for multiple items uploading if
351 * (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
352 * Button createDirBtn = new Button(this);
353 * createDirBtn.setId(android.R.id.button1);
354 * createDirBtn.setText(R.string.uploader_btn_create_dir_text);
355 * createDirBtn.setOnClickListener(this); ((LinearLayout)
356 * findViewById(R.id.linearLayout1)).addView( createDirBtn,
357 * LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); }
358 *
359 }*/
360 }
361
362 private void prepareStreamsToUpload() {
363 if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
364 mStreamsToUpload = new ArrayList<Parcelable>();
365 mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
366 } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
367 mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
368 } else {
369 // unknow action inserted
370 throw new IllegalArgumentException("Unknown action given: " + getIntent().getAction());
371 }
372 }
373
374 public void uploadFiles() {
375 try {
376 WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());
377 wdc.allowSelfsignedCertificates();
378
379 // create last directory in path if necessary
380 if (mCreateDir) {
381 wdc.createDirectory(mUploadPath);
382 }
383
384 String[] local = new String[mStreamsToUpload.size()], remote = new String[mStreamsToUpload.size()];
385
386 for (int i = 0; i < mStreamsToUpload.size(); ++i) {
387 Uri uri = (Uri) mStreamsToUpload.get(i);
388 if (uri.getScheme().equals("content")) {
389 Cursor c = getContentResolver().query((Uri) mStreamsToUpload.get(i),
390 CONTENT_PROJECTION,
391 null,
392 null,
393 null);
394
395 if (!c.moveToFirst())
396 continue;
397
398 final String display_name = c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
399 data = c.getString(c.getColumnIndex(Media.DATA));
400 local[i] = data;
401 remote[i] = mUploadPath + display_name;
402 } else if (uri.getScheme().equals("file")) {
403 final File file = new File(Uri.decode(uri.toString()).replace(uri.getScheme() + "://", ""));
404 local[i] = file.getAbsolutePath();
405 remote[i] = mUploadPath + file.getName();
406 }
407
408 }
409 Intent intent = new Intent(getApplicationContext(), FileUploader.class);
410 intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
411 intent.putExtra(FileUploader.KEY_LOCAL_FILE, local);
412 intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote);
413 intent.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
414 startService(intent);
415 finish();
416
417 } catch (SecurityException e) {
418 Toast.makeText(this, getString(R.string.uploader_error_forbidden_content), Toast.LENGTH_LONG).show();
419 }
420 }
421
422 }