Fix for :
[pub/Android/ownCloud.git] / src / com / owncloud / android / Uploader.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19 package com.owncloud.android;
20
21 import java.io.File;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Stack;
27 import java.util.Vector;
28
29 import android.accounts.Account;
30 import android.accounts.AccountManager;
31 import android.app.AlertDialog;
32 import android.app.AlertDialog.Builder;
33 import android.app.Dialog;
34 import android.app.ListActivity;
35 import android.app.ProgressDialog;
36 import android.content.Context;
37 import android.content.DialogInterface;
38 import android.content.DialogInterface.OnCancelListener;
39 import android.content.DialogInterface.OnClickListener;
40 import android.content.Intent;
41 import android.database.Cursor;
42 import android.net.Uri;
43 import android.os.Bundle;
44 import android.os.Parcelable;
45 import android.provider.MediaStore.Audio;
46 import android.provider.MediaStore.Images;
47 import android.provider.MediaStore.Video;
48 import android.util.Log;
49 import android.view.View;
50 import android.view.Window;
51 import android.widget.AdapterView;
52 import android.widget.AdapterView.OnItemClickListener;
53 import android.widget.Button;
54 import android.widget.EditText;
55 import android.widget.SimpleAdapter;
56 import android.widget.Toast;
57
58 import com.owncloud.android.authenticator.AccountAuthenticator;
59 import com.owncloud.android.datamodel.DataStorageManager;
60 import com.owncloud.android.datamodel.FileDataStorageManager;
61 import com.owncloud.android.datamodel.OCFile;
62 import com.owncloud.android.files.services.FileUploader;
63 import com.owncloud.android.network.OwnCloudClientUtils;
64
65 import eu.alefzero.webdav.WebdavClient;
66
67 /**
68 * This can be used to upload things to an ownCloud instance.
69 *
70 * @author Bartek Przybylski
71 *
72 */
73 public class Uploader extends ListActivity implements OnItemClickListener, android.view.View.OnClickListener {
74 private static final String TAG = "ownCloudUploader";
75
76 private Account mAccount;
77 private AccountManager mAccountManager;
78 private Stack<String> mParents;
79 private ArrayList<Parcelable> mStreamsToUpload;
80 private boolean mCreateDir;
81 private String mUploadPath;
82 private DataStorageManager mStorageManager;
83 private OCFile mFile;
84
85 private final static int DIALOG_NO_ACCOUNT = 0;
86 private final static int DIALOG_WAITING = 1;
87 private final static int DIALOG_NO_STREAM = 2;
88 private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
89 //private final static int DIALOG_GET_DIRNAME = 4;
90
91 private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
92
93 @Override
94 protected void onCreate(Bundle savedInstanceState) {
95 super.onCreate(savedInstanceState);
96 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
97 mParents = new Stack<String>();
98 mParents.add("");
99 /*if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
100 prepareStreamsToUpload();*/
101 if (prepareStreamsToUpload()) {
102 mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
103 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
104 if (accounts.length == 0) {
105 Log.i(TAG, "No ownCloud account is available");
106 showDialog(DIALOG_NO_ACCOUNT);
107 } else if (accounts.length > 1) {
108 Log.i(TAG, "More then one ownCloud is available");
109 showDialog(DIALOG_MULTIPLE_ACCOUNT);
110 } else {
111 mAccount = accounts[0];
112 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
113 populateDirectoryList();
114 }
115 } else {
116 showDialog(DIALOG_NO_STREAM);
117 }
118 }
119
120 @Override
121 protected Dialog onCreateDialog(final int id) {
122 final AlertDialog.Builder builder = new Builder(this);
123 switch (id) {
124 case DIALOG_WAITING:
125 ProgressDialog pDialog = new ProgressDialog(this);
126 pDialog.setIndeterminate(false);
127 pDialog.setCancelable(false);
128 pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));
129 return pDialog;
130 case DIALOG_NO_ACCOUNT:
131 builder.setIcon(android.R.drawable.ic_dialog_alert);
132 builder.setTitle(R.string.uploader_wrn_no_account_title);
133 builder.setMessage(String.format(getString(R.string.uploader_wrn_no_account_text), getString(R.string.app_name)));
134 builder.setCancelable(false);
135 builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
136 @Override
137 public void onClick(DialogInterface dialog, int which) {
138 if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
139 // using string value since in API7 this
140 // constatn is not defined
141 // in API7 < this constatant is defined in
142 // Settings.ADD_ACCOUNT_SETTINGS
143 // and Settings.EXTRA_AUTHORITIES
144 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
145 intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
146 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
147 } else {
148 // since in API7 there is no direct call for
149 // account setup, so we need to
150 // show our own AccountSetupAcricity, get
151 // desired results and setup
152 // everything for ourself
153 Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
154 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
155 }
156 }
157 });
158 builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
159 @Override
160 public void onClick(DialogInterface dialog, int which) {
161 finish();
162 }
163 });
164 return builder.create();
165 case DIALOG_MULTIPLE_ACCOUNT:
166 CharSequence ac[] = new CharSequence[mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE).length];
167 for (int i = 0; i < ac.length; ++i) {
168 ac[i] = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[i].name;
169 }
170 builder.setTitle(R.string.common_choose_account);
171 builder.setItems(ac, new OnClickListener() {
172 @Override
173 public void onClick(DialogInterface dialog, int which) {
174 mAccount = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];
175 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
176 populateDirectoryList();
177 }
178 });
179 builder.setCancelable(true);
180 builder.setOnCancelListener(new OnCancelListener() {
181 @Override
182 public void onCancel(DialogInterface dialog) {
183 dialog.cancel();
184 finish();
185 }
186 });
187 return builder.create();
188 case DIALOG_NO_STREAM:
189 builder.setIcon(android.R.drawable.ic_dialog_alert);
190 builder.setTitle(R.string.uploader_wrn_no_content_title);
191 builder.setMessage(R.string.uploader_wrn_no_content_text);
192 builder.setCancelable(false);
193 builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
194 @Override
195 public void onClick(DialogInterface dialog, int which) {
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 @Override
215 public void onClick(DialogInterface dialog, int which) {
216 Uploader.this.mUploadPath = mPath + mDirname.getText().toString();
217 Uploader.this.mCreateDir = true;
218 uploadFiles();
219 }
220 }
221
222 @Override
223 public void onBackPressed() {
224
225 if (mParents.size() <= 1) {
226 super.onBackPressed();
227 return;
228 } else {
229 mParents.pop();
230 populateDirectoryList();
231 }
232 }
233
234 @Override
235 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
236 // click on folder in the list
237 Log.d(TAG, "on item click");
238 Vector<OCFile> tmpfiles = mStorageManager.getDirectoryContent(mFile);
239 if (tmpfiles.size() <= 0) return;
240 // filter on dirtype
241 Vector<OCFile> files = new Vector<OCFile>();
242 for (OCFile f : tmpfiles)
243 if (f.isDirectory())
244 files.add(f);
245 if (files.size() < position) {
246 throw new IndexOutOfBoundsException("Incorrect item selected");
247 }
248 mParents.push(files.get(position).getFileName());
249 populateDirectoryList();
250 }
251
252 @Override
253 public void onClick(View v) {
254 // click on button
255 switch (v.getId()) {
256 case R.id.uploader_choose_folder:
257 mUploadPath = ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
258 for (String p : mParents)
259 mUploadPath += p + OCFile.PATH_SEPARATOR;
260 Log.d(TAG, "Uploading file to dir " + mUploadPath);
261
262 uploadFiles();
263
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 List<HashMap<String, Object>> data = new LinkedList<HashMap<String,Object>>();
305 for (OCFile f : files) {
306 HashMap<String, Object> h = new HashMap<String, Object>();
307 if (f.isDirectory()) {
308 h.put("dirname", f.getFileName());
309 data.add(h);
310 }
311 }
312 SimpleAdapter sa = new SimpleAdapter(this,
313 data,
314 R.layout.uploader_list_item_layout,
315 new String[] {"dirname"},
316 new int[] {R.id.textView1});
317 setListAdapter(sa);
318 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
319 btn.setOnClickListener(this);
320 getListView().setOnItemClickListener(this);
321 }
322 }
323
324 private boolean prepareStreamsToUpload() {
325 if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
326 mStreamsToUpload = new ArrayList<Parcelable>();
327 mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
328 } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
329 mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
330 }
331 return (mStreamsToUpload != null && mStreamsToUpload.get(0) != null);
332 }
333
334 public void uploadFiles() {
335 try {
336 WebdavClient webdav = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
337
338 ArrayList<String> local = new ArrayList<String>();
339 ArrayList<String> remote = new ArrayList<String>();
340
341 // create last directory in path if necessary
342 if (mCreateDir) {
343 webdav.createDirectory(mUploadPath);
344 }
345 // this checks the mimeType
346 for (Parcelable mStream : mStreamsToUpload) {
347
348 Uri uri = (Uri) mStream;
349 if (uri !=null) {
350 if (uri.getScheme().equals("content")) {
351
352 String mimeType = getContentResolver().getType(uri);
353
354 if (mimeType.contains("image")) {
355 String[] CONTENT_PROJECTION = { Images.Media.DATA, Images.Media.DISPLAY_NAME, Images.Media.MIME_TYPE, Images.Media.SIZE};
356 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
357 c.moveToFirst();
358 int index = c.getColumnIndex(Images.Media.DATA);
359 String data = c.getString(index);
360 local.add(data);
361 remote.add(mUploadPath + c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME)));
362
363 }
364 else if (mimeType.contains("video")) {
365 String[] CONTENT_PROJECTION = { Video.Media.DATA, Video.Media.DISPLAY_NAME, Video.Media.MIME_TYPE, Video.Media.SIZE, Video.Media.DATE_MODIFIED };
366 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
367 c.moveToFirst();
368 int index = c.getColumnIndex(Video.Media.DATA);
369 String data = c.getString(index);
370 local.add(data);
371 remote.add(mUploadPath + c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME)));
372
373 }
374 else if (mimeType.contains("audio")) {
375 String[] CONTENT_PROJECTION = { Audio.Media.DATA, Audio.Media.DISPLAY_NAME, Audio.Media.MIME_TYPE, Audio.Media.SIZE };
376 Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null, null, null);
377 c.moveToFirst();
378 int index = c.getColumnIndex(Audio.Media.DATA);
379 String data = c.getString(index);
380 local.add(data);
381 remote.add(mUploadPath + c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME)));
382
383 }
384 else {
385 String filePath = Uri.decode(uri.toString()).replace(uri.getScheme() + "://", "");
386 // cut everything whats before mnt. It occured to me that sometimes apps send their name into the URI
387 if (filePath.contains("mnt")) {
388 String splitedFilePath[] = filePath.split("/mnt");
389 filePath = splitedFilePath[1];
390 }
391 final File file = new File(filePath);
392 local.add(file.getAbsolutePath());
393 remote.add(mUploadPath + file.getName());
394 }
395
396 } else if (uri.getScheme().equals("file")) {
397 String filePath = Uri.decode(uri.toString()).replace(uri.getScheme() + "://", "");
398 if (filePath.contains("mnt")) {
399 String splitedFilePath[] = filePath.split("/mnt");
400 filePath = splitedFilePath[1];
401 }
402 final File file = new File(filePath);
403 local.add(file.getAbsolutePath());
404 remote.add(mUploadPath + file.getName());
405 }
406 else {
407 throw new SecurityException();
408 }
409 }
410 else {
411 throw new SecurityException();
412 }
413
414 Intent intent = new Intent(getApplicationContext(), FileUploader.class);
415 intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
416 intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()]));
417 intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote.toArray(new String[remote.size()]));
418 intent.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
419 startService(intent);
420 finish();
421 }
422 } catch (SecurityException e) {
423 String message = String.format(getString(R.string.uploader_error_forbidden_content), getString(R.string.app_name));
424 Toast.makeText(this, message, Toast.LENGTH_LONG).show();
425 }
426 }
427
428 }