6f650d7b9eb379199dcae483634bb68ef59d1d74
[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.utils.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 mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
101 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
102 if (accounts.length == 0) {
103 Log.i(TAG, "No ownCloud account is available");
104 showDialog(DIALOG_NO_ACCOUNT);
105 } else if (accounts.length > 1) {
106 Log.i(TAG, "More then one ownCloud is available");
107 showDialog(DIALOG_MULTIPLE_ACCOUNT);
108 } else {
109 mAccount = accounts[0];
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 case DIALOG_NO_STREAM:
205 builder.setIcon(android.R.drawable.ic_dialog_alert);
206 builder.setTitle(R.string.uploader_wrn_no_content_title);
207 builder.setMessage(R.string.uploader_wrn_no_content_text);
208 builder.setCancelable(false);
209 builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
210 public void onClick(DialogInterface dialog, int which) {
211 finish();
212 }
213 });
214 return builder.create();
215 default:
216 throw new IllegalArgumentException("Unknown dialog id: " + id);
217 }
218 }
219
220 class a implements OnClickListener {
221 String mPath;
222 EditText mDirname;
223
224 public a(String path, EditText dirname) {
225 mPath = path;
226 mDirname = dirname;
227 }
228
229 public void onClick(DialogInterface dialog, int which) {
230 Uploader.this.mUploadPath = mPath + mDirname.getText().toString();
231 Uploader.this.mCreateDir = true;
232 uploadFiles();
233 }
234 }
235
236 @Override
237 public void onBackPressed() {
238
239 if (mParents.size() <= 1) {
240 super.onBackPressed();
241 return;
242 } else {
243 mParents.pop();
244 populateDirectoryList();
245 }
246 }
247
248 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
249 // click on folder in the list
250 Log.d(TAG, "on item click");
251 Vector<OCFile> tmpfiles = mStorageManager.getDirectoryContent(mFile);
252 if (tmpfiles == null) return;
253 // filter on dirtype
254 Vector<OCFile> files = new Vector<OCFile>();
255 for (OCFile f : tmpfiles)
256 if (f.isDirectory())
257 files.add(f);
258 if (files.size() < position) {
259 throw new IndexOutOfBoundsException("Incorrect item selected");
260 }
261 mParents.push(files.get(position).getFileName());
262 populateDirectoryList();
263 }
264
265 public void onClick(View v) {
266 // click on button
267 switch (v.getId()) {
268 case R.id.uploader_choose_folder:
269 mUploadPath = ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
270 for (String p : mParents)
271 mUploadPath += p + OCFile.PATH_SEPARATOR;
272 Log.d(TAG, "Uploading file to dir " + mUploadPath);
273
274 uploadFiles();
275
276 break;
277 /*case android.R.id.button1: // dynamic action for create aditional dir
278 showDialog(DIALOG_GET_DIRNAME);
279 break;*/
280 default:
281 throw new IllegalArgumentException("Wrong element clicked");
282 }
283 }
284
285 @Override
286 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
287 super.onActivityResult(requestCode, resultCode, data);
288 Log.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
289 if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
290 dismissDialog(DIALOG_NO_ACCOUNT);
291 if (resultCode == RESULT_CANCELED) {
292 finish();
293 }
294 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);
295 if (accounts.length == 0) {
296 showDialog(DIALOG_NO_ACCOUNT);
297 } else {
298 // there is no need for checking for is there more then one
299 // account at this point
300 // since account setup can set only one account at time
301 mAccount = accounts[0];
302 populateDirectoryList();
303 }
304 }
305 }
306
307 private void populateDirectoryList() {
308 setContentView(R.layout.uploader_layout);
309
310 String full_path = "";
311 for (String a : mParents)
312 full_path += a + "/";
313
314 Log.d(TAG, "Populating view with content of : " + full_path);
315
316 mFile = mStorageManager.getFileByPath(full_path);
317 if (mFile != null) {
318 Vector<OCFile> files = mStorageManager.getDirectoryContent(mFile);
319 if (files != null) {
320 List<HashMap<String, Object>> data = new LinkedList<HashMap<String,Object>>();
321 for (OCFile f : files) {
322 HashMap<String, Object> h = new HashMap<String, Object>();
323 if (f.isDirectory()) {
324 h.put("dirname", f.getFileName());
325 data.add(h);
326 }
327 }
328 SimpleAdapter sa = new SimpleAdapter(this,
329 data,
330 R.layout.uploader_list_item_layout,
331 new String[] {"dirname"},
332 new int[] {R.id.textView1});
333 setListAdapter(sa);
334 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
335 btn.setOnClickListener(this);
336 getListView().setOnItemClickListener(this);
337 }
338 }
339 /*
340 mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI, null, ProviderTableMeta.FILE_NAME
341 + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { "/", mAccount.name }, null);
342
343 if (mCursor.moveToFirst()) {
344 mCursor = managedQuery(
345 ProviderMeta.ProviderTableMeta.CONTENT_URI,
346 null,
347 ProviderTableMeta.FILE_CONTENT_TYPE + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND "
348 + ProviderTableMeta.FILE_PARENT + "=?",
349 new String[] { "DIR", mAccount.name,
350 mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta._ID)) }, null);
351
352 ListView lv = getListView();
353 lv.setOnItemClickListener(this);
354 SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.uploader_list_item_layout, mCursor,
355 new String[] { ProviderTableMeta.FILE_NAME }, new int[] { R.id.textView1 });
356 setListAdapter(sca);
357 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
358 btn.setOnClickListener(this);
359 /*
360 * disable this until new server interaction service wont be created
361 * // insert create new directory for multiple items uploading if
362 * (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
363 * Button createDirBtn = new Button(this);
364 * createDirBtn.setId(android.R.id.button1);
365 * createDirBtn.setText(R.string.uploader_btn_create_dir_text);
366 * createDirBtn.setOnClickListener(this); ((LinearLayout)
367 * findViewById(R.id.linearLayout1)).addView( createDirBtn,
368 * LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); }
369 *
370 }*/
371 }
372
373 private void prepareStreamsToUpload() {
374 if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
375 mStreamsToUpload = new ArrayList<Parcelable>();
376 mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
377 } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
378 mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
379 } else {
380 // unknow action inserted
381 throw new IllegalArgumentException("Unknown action given: " + getIntent().getAction());
382 }
383 }
384
385 public void uploadFiles() {
386 try {
387 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
388
389 // create last directory in path if necessary
390 if (mCreateDir) {
391 wdc.createDirectory(mUploadPath);
392 }
393
394 String[] local = new String[mStreamsToUpload.size()], remote = new String[mStreamsToUpload.size()];
395
396 for (int i = 0; i < mStreamsToUpload.size(); ++i) {
397 Uri uri = (Uri) mStreamsToUpload.get(i);
398 if (uri.getScheme().equals("content")) {
399 Cursor c = getContentResolver().query((Uri) mStreamsToUpload.get(i),
400 CONTENT_PROJECTION,
401 null,
402 null,
403 null);
404
405 if (!c.moveToFirst())
406 continue;
407
408 final String display_name = c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
409 data = c.getString(c.getColumnIndex(Media.DATA));
410 local[i] = data;
411 remote[i] = mUploadPath + display_name;
412 } else if (uri.getScheme().equals("file")) {
413 final File file = new File(Uri.decode(uri.toString()).replace(uri.getScheme() + "://", ""));
414 local[i] = file.getAbsolutePath();
415 remote[i] = mUploadPath + file.getName();
416 }
417
418 }
419 Intent intent = new Intent(getApplicationContext(), FileUploader.class);
420 intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
421 intent.putExtra(FileUploader.KEY_LOCAL_FILE, local);
422 intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote);
423 intent.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
424 startService(intent);
425 finish();
426
427 } catch (SecurityException e) {
428 Toast.makeText(this, getString(R.string.uploader_error_forbidden_content), Toast.LENGTH_LONG).show();
429 }
430 }
431
432 }