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