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