Merge branch 'master' into oauth_login
[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
63 /**
64 * This can be used to upload things to an ownCloud instance.
65 *
66 * @author Bartek Przybylski
67 *
68 */
69 public class Uploader extends ListActivity implements OnItemClickListener, android.view.View.OnClickListener {
70 private static final String TAG = "ownCloudUploader";
71
72 private Account mAccount;
73 private AccountManager mAccountManager;
74 private Stack<String> mParents;
75 private ArrayList<Parcelable> mStreamsToUpload;
76 private boolean mCreateDir;
77 private String mUploadPath;
78 private static final String[] CONTENT_PROJECTION = { Media.DATA, Media.DISPLAY_NAME, Media.MIME_TYPE, Media.SIZE };
79 private DataStorageManager mStorageManager;
80 private OCFile mFile;
81
82 private final static int DIALOG_NO_ACCOUNT = 0;
83 private final static int DIALOG_WAITING = 1;
84 private final static int DIALOG_NO_STREAM = 2;
85 private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
86 //private final static int DIALOG_GET_DIRNAME = 4;
87
88 private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
89
90 @Override
91 protected void onCreate(Bundle savedInstanceState) {
92 super.onCreate(savedInstanceState);
93 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
94 mParents = new Stack<String>();
95 mParents.add("");
96 /*if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
97 prepareStreamsToUpload();*/
98 if (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 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
110 populateDirectoryList();
111 }
112 } else {
113 showDialog(DIALOG_NO_STREAM);
114 }
115 }
116
117 @Override
118 protected Dialog onCreateDialog(final int id) {
119 final AlertDialog.Builder builder = new Builder(this);
120 switch (id) {
121 case DIALOG_WAITING:
122 ProgressDialog pDialog = new ProgressDialog(this);
123 pDialog.setIndeterminate(false);
124 pDialog.setCancelable(false);
125 pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));
126 return pDialog;
127 case DIALOG_NO_ACCOUNT:
128 builder.setIcon(android.R.drawable.ic_dialog_alert);
129 builder.setTitle(R.string.uploader_wrn_no_account_title);
130 builder.setMessage(String.format(getString(R.string.uploader_wrn_no_account_text), getString(R.string.app_name)));
131 builder.setCancelable(false);
132 builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
133 @Override
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 @Override
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 @Override
192 public void onClick(DialogInterface dialog, int which) {
193 mAccount = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];
194 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
195 populateDirectoryList();
196 }
197 });
198 builder.setCancelable(true);
199 builder.setOnCancelListener(new OnCancelListener() {
200 @Override
201 public void onCancel(DialogInterface dialog) {
202 dialog.cancel();
203 finish();
204 }
205 });
206 return builder.create();
207 case DIALOG_NO_STREAM:
208 builder.setIcon(android.R.drawable.ic_dialog_alert);
209 builder.setTitle(R.string.uploader_wrn_no_content_title);
210 builder.setMessage(R.string.uploader_wrn_no_content_text);
211 builder.setCancelable(false);
212 builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
213 @Override
214 public void onClick(DialogInterface dialog, int which) {
215 finish();
216 }
217 });
218 return builder.create();
219 default:
220 throw new IllegalArgumentException("Unknown dialog id: " + id);
221 }
222 }
223
224 class a implements OnClickListener {
225 String mPath;
226 EditText mDirname;
227
228 public a(String path, EditText dirname) {
229 mPath = path;
230 mDirname = dirname;
231 }
232
233 @Override
234 public void onClick(DialogInterface dialog, int which) {
235 Uploader.this.mUploadPath = mPath + mDirname.getText().toString();
236 Uploader.this.mCreateDir = true;
237 uploadFiles();
238 }
239 }
240
241 @Override
242 public void onBackPressed() {
243
244 if (mParents.size() <= 1) {
245 super.onBackPressed();
246 return;
247 } else {
248 mParents.pop();
249 populateDirectoryList();
250 }
251 }
252
253 @Override
254 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
255 // click on folder in the list
256 Log.d(TAG, "on item click");
257 Vector<OCFile> tmpfiles = mStorageManager.getDirectoryContent(mFile);
258 if (tmpfiles.size() <= 0) return;
259 // filter on dirtype
260 Vector<OCFile> files = new Vector<OCFile>();
261 for (OCFile f : tmpfiles)
262 if (f.isDirectory())
263 files.add(f);
264 if (files.size() < position) {
265 throw new IndexOutOfBoundsException("Incorrect item selected");
266 }
267 mParents.push(files.get(position).getFileName());
268 populateDirectoryList();
269 }
270
271 @Override
272 public void onClick(View v) {
273 // click on button
274 switch (v.getId()) {
275 case R.id.uploader_choose_folder:
276 mUploadPath = ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
277 for (String p : mParents)
278 mUploadPath += p + OCFile.PATH_SEPARATOR;
279 Log.d(TAG, "Uploading file to dir " + mUploadPath);
280
281 uploadFiles();
282
283 break;
284 /*case android.R.id.button1: // dynamic action for create aditional dir
285 showDialog(DIALOG_GET_DIRNAME);
286 break;*/
287 default:
288 throw new IllegalArgumentException("Wrong element clicked");
289 }
290 }
291
292 @Override
293 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
294 super.onActivityResult(requestCode, resultCode, data);
295 Log.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
296 if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
297 dismissDialog(DIALOG_NO_ACCOUNT);
298 if (resultCode == RESULT_CANCELED) {
299 finish();
300 }
301 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);
302 if (accounts.length == 0) {
303 showDialog(DIALOG_NO_ACCOUNT);
304 } else {
305 // there is no need for checking for is there more then one
306 // account at this point
307 // since account setup can set only one account at time
308 mAccount = accounts[0];
309 populateDirectoryList();
310 }
311 }
312 }
313
314 private void populateDirectoryList() {
315 setContentView(R.layout.uploader_layout);
316
317 String full_path = "";
318 for (String a : mParents)
319 full_path += a + "/";
320
321 Log.d(TAG, "Populating view with content of : " + full_path);
322
323 mFile = mStorageManager.getFileByPath(full_path);
324 if (mFile != null) {
325 Vector<OCFile> files = mStorageManager.getDirectoryContent(mFile);
326 List<HashMap<String, Object>> data = new LinkedList<HashMap<String,Object>>();
327 for (OCFile f : files) {
328 HashMap<String, Object> h = new HashMap<String, Object>();
329 if (f.isDirectory()) {
330 h.put("dirname", f.getFileName());
331 data.add(h);
332 }
333 }
334 SimpleAdapter sa = new SimpleAdapter(this,
335 data,
336 R.layout.uploader_list_item_layout,
337 new String[] {"dirname"},
338 new int[] {R.id.textView1});
339 setListAdapter(sa);
340 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
341 btn.setOnClickListener(this);
342 getListView().setOnItemClickListener(this);
343 }
344 }
345
346 private boolean prepareStreamsToUpload() {
347 if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
348 mStreamsToUpload = new ArrayList<Parcelable>();
349 mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
350 } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
351 mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
352 }
353 return (mStreamsToUpload != null && mStreamsToUpload.get(0) != null);
354 }
355
356 public void uploadFiles() {
357 try {
358 /* TODO - mCreateDir can never be true at this moment; we will replace wdc.createDirectory by CreateFolderOperation when that is fixed
359 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
360 // create last directory in path if necessary
361 if (mCreateDir) {
362 wdc.createDirectory(mUploadPath);
363 }
364 */
365
366 String[] local = new String[mStreamsToUpload.size()], remote = new String[mStreamsToUpload.size()];
367
368 for (int i = 0; i < mStreamsToUpload.size(); ++i) {
369 Uri uri = (Uri) mStreamsToUpload.get(i);
370 if (uri.getScheme().equals("content")) {
371 Cursor c = getContentResolver().query((Uri) mStreamsToUpload.get(i),
372 CONTENT_PROJECTION,
373 null,
374 null,
375 null);
376
377 if (!c.moveToFirst())
378 continue;
379
380 final String display_name = c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
381 data = c.getString(c.getColumnIndex(Media.DATA));
382 local[i] = data;
383 remote[i] = mUploadPath + display_name;
384 } else if (uri.getScheme().equals("file")) {
385 final File file = new File(Uri.decode(uri.toString()).replace(uri.getScheme() + "://", ""));
386 local[i] = file.getAbsolutePath();
387 remote[i] = mUploadPath + file.getName();
388 }
389
390 }
391 Intent intent = new Intent(getApplicationContext(), FileUploader.class);
392 intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
393 intent.putExtra(FileUploader.KEY_LOCAL_FILE, local);
394 intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote);
395 intent.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
396 startService(intent);
397 finish();
398
399 } catch (SecurityException e) {
400 String message = String.format(getString(R.string.uploader_error_forbidden_content), getString(R.string.app_name));
401 Toast.makeText(this, message, Toast.LENGTH_LONG).show();
402 }
403 }
404
405 }