2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * Copyright (C) 2012 Bartek Przybylski
6 * Copyright (C) 2015 ownCloud Inc.
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2,
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 package com
.owncloud
.android
.ui
.activity
;
25 import java
.io
.FileDescriptor
;
26 import java
.io
.FileInputStream
;
27 import java
.io
.FileNotFoundException
;
28 import java
.io
.FileOutputStream
;
29 import java
.io
.IOException
;
30 import java
.io
.InputStream
;
31 import java
.util
.ArrayList
;
32 import java
.util
.HashMap
;
33 import java
.util
.LinkedList
;
34 import java
.util
.List
;
35 import java
.util
.Stack
;
36 import java
.util
.Vector
;
37 import java
.util
.concurrent
.ExecutionException
;
39 import android
.accounts
.Account
;
40 import android
.accounts
.AccountManager
;
41 import android
.app
.AlertDialog
;
42 import android
.app
.AlertDialog
.Builder
;
43 import android
.app
.Dialog
;
44 import android
.app
.ProgressDialog
;
45 import android
.content
.Context
;
46 import android
.content
.DialogInterface
;
47 import android
.content
.DialogInterface
.OnCancelListener
;
48 import android
.content
.DialogInterface
.OnClickListener
;
49 import android
.content
.Intent
;
50 import android
.content
.SharedPreferences
;
51 import android
.content
.res
.Resources
.NotFoundException
;
52 import android
.database
.Cursor
;
53 import android
.net
.Uri
;
54 import android
.os
.Bundle
;
55 import android
.os
.ParcelFileDescriptor
;
56 import android
.os
.Parcelable
;
57 import android
.preference
.PreferenceManager
;
58 import android
.provider
.MediaStore
.Audio
;
59 import android
.provider
.MediaStore
.Images
;
60 import android
.provider
.MediaStore
.Video
;
61 import android
.view
.View
;
62 import android
.widget
.AdapterView
;
63 import android
.widget
.AdapterView
.OnItemClickListener
;
64 import android
.widget
.Button
;
65 import android
.widget
.EditText
;
66 import android
.widget
.ListView
;
67 import android
.widget
.SimpleAdapter
;
68 import android
.widget
.Toast
;
70 import com
.actionbarsherlock
.app
.ActionBar
;
71 import com
.actionbarsherlock
.view
.MenuItem
;
72 import com
.owncloud
.android
.MainApp
;
73 import com
.owncloud
.android
.R
;
74 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
75 import com
.owncloud
.android
.datamodel
.OCFile
;
76 import com
.owncloud
.android
.files
.services
.FileUploader
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
81 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
82 import com
.owncloud
.android
.utils
.CopyTmpFileAsyncTask
;
83 import com
.owncloud
.android
.utils
.DisplayUtils
;
84 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
85 import com
.owncloud
.android
.utils
.FileStorageUtils
;
86 import com
.owncloud
.android
.utils
.UriUtils
;
90 * This can be used to upload things to an ownCloud instance.
92 public class Uploader
extends FileActivity
93 implements OnItemClickListener
, android
.view
.View
.OnClickListener
,
94 CopyTmpFileAsyncTask
.OnCopyTmpFileTaskListener
{
96 private static final String TAG
= Uploader
.class.getSimpleName();
98 private AccountManager mAccountManager
;
99 private Stack
<String
> mParents
;
100 private ArrayList
<Parcelable
> mStreamsToUpload
;
101 private boolean mCreateDir
;
102 private String mUploadPath
;
103 private OCFile mFile
;
104 private boolean mAccountSelected
;
106 private final static int DIALOG_NO_ACCOUNT
= 0;
107 private final static int DIALOG_WAITING
= 1;
108 private final static int DIALOG_NO_STREAM
= 2;
109 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
111 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
113 private final static String KEY_PARENTS
= "PARENTS";
114 private final static String KEY_FILE
= "FILE";
115 private final static String KEY_ACCOUNT_SELECTED
= "ACCOUNT_SELECTED";
118 protected void onCreate(Bundle savedInstanceState
) {
119 prepareStreamsToUpload();
121 if (savedInstanceState
== null
) {
122 mParents
= new Stack
<String
>();
123 mAccountSelected
= false
;
125 mParents
= (Stack
<String
>) savedInstanceState
.getSerializable(KEY_PARENTS
);
126 mFile
= savedInstanceState
.getParcelable(KEY_FILE
);
127 mAccountSelected
= savedInstanceState
.getBoolean(KEY_ACCOUNT_SELECTED
);
129 super.onCreate(savedInstanceState
);
131 ActionBar actionBar
= getSupportActionBar();
132 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
137 protected void setAccount(Account account
, boolean savedAccount
) {
138 if (somethingToUpload()) {
139 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
140 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAccountType());
141 if (accounts
.length
== 0) {
142 Log_OC
.i(TAG
, "No ownCloud account is available");
143 showDialog(DIALOG_NO_ACCOUNT
);
144 } else if (accounts
.length
> 1 && !mAccountSelected
) {
145 Log_OC
.i(TAG
, "More than one ownCloud is available");
146 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
149 setAccount(accounts
[0]);
154 showDialog(DIALOG_NO_STREAM
);
157 super.setAccount(account
, savedAccount
);
161 protected void onAccountSet(boolean stateWasRecovered
) {
162 super.onAccountSet(mAccountWasRestored
);
164 populateDirectoryList();
168 protected void onSaveInstanceState(Bundle outState
) {
169 Log_OC
.d(TAG
, "onSaveInstanceState() start");
170 super.onSaveInstanceState(outState
);
171 outState
.putSerializable(KEY_PARENTS
, mParents
);
172 //outState.putParcelable(KEY_ACCOUNT, mAccount);
173 outState
.putParcelable(KEY_FILE
, mFile
);
174 outState
.putBoolean(KEY_ACCOUNT_SELECTED
, mAccountSelected
);
176 Log_OC
.d(TAG
, "onSaveInstanceState() end");
180 protected Dialog
onCreateDialog(final int id
) {
181 final AlertDialog
.Builder builder
= new Builder(this);
184 ProgressDialog pDialog
= new ProgressDialog(this);
185 pDialog
.setIndeterminate(false
);
186 pDialog
.setCancelable(false
);
187 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
189 case DIALOG_NO_ACCOUNT
:
190 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
191 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
192 builder
.setMessage(String
.format(
193 getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
194 builder
.setCancelable(false
);
195 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
197 public void onClick(DialogInterface dialog
, int which
) {
198 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
199 // using string value since in API7 this
200 // constatn is not defined
201 // in API7 < this constatant is defined in
202 // Settings.ADD_ACCOUNT_SETTINGS
203 // and Settings.EXTRA_AUTHORITIES
204 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
205 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
206 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
208 // since in API7 there is no direct call for
209 // account setup, so we need to
210 // show our own AccountSetupAcricity, get
211 // desired results and setup
212 // everything for ourself
213 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
214 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
218 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
220 public void onClick(DialogInterface dialog
, int which
) {
224 return builder
.create();
225 case DIALOG_MULTIPLE_ACCOUNT
:
226 CharSequence ac
[] = new CharSequence
[
227 mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
228 for (int i
= 0; i
< ac
.length
; ++i
) {
229 ac
[i
] = DisplayUtils
.convertIdn(
230 mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
232 builder
.setTitle(R
.string
.common_choose_account
);
233 builder
.setItems(ac
, new OnClickListener() {
235 public void onClick(DialogInterface dialog
, int which
) {
236 setAccount(mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
]);
237 onAccountSet(mAccountWasRestored
);
239 mAccountSelected
= true
;
242 builder
.setCancelable(true
);
243 builder
.setOnCancelListener(new OnCancelListener() {
245 public void onCancel(DialogInterface dialog
) {
250 return builder
.create();
251 case DIALOG_NO_STREAM
:
252 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
253 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
254 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
255 builder
.setCancelable(false
);
256 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
258 public void onClick(DialogInterface dialog
, int which
) {
262 return builder
.create();
264 throw new IllegalArgumentException("Unknown dialog id: " + id
);
268 class a
implements OnClickListener
{
272 public a(String path
, EditText dirname
) {
278 public void onClick(DialogInterface dialog
, int which
) {
279 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
280 Uploader
.this.mCreateDir
= true
;
286 public void onBackPressed() {
288 if (mParents
.size() <= 1) {
289 super.onBackPressed();
293 populateDirectoryList();
298 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
299 // click on folder in the list
300 Log_OC
.d(TAG
, "on item click");
301 Vector
<OCFile
> tmpfiles
= getStorageManager().getFolderContent(mFile
);
302 if (tmpfiles
.size() <= 0) return;
304 Vector
<OCFile
> files
= new Vector
<OCFile
>();
305 for (OCFile f
: tmpfiles
)
308 if (files
.size() < position
) {
309 throw new IndexOutOfBoundsException("Incorrect item selected");
311 mParents
.push(files
.get(position
).getFileName());
312 populateDirectoryList();
316 public void onClick(View v
) {
319 case R
.id
.uploader_choose_folder
:
320 mUploadPath
= ""; // first element in mParents is root dir, represented by "";
321 // init mUploadPath with "/" results in a "//" prefix
322 for (String p
: mParents
)
323 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
324 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
330 case R
.id
.uploader_new_folder
:
331 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(mFile
);
332 dialog
.show(getSupportFragmentManager(), "createdirdialog");
337 throw new IllegalArgumentException("Wrong element clicked");
342 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
343 super.onActivityResult(requestCode
, resultCode
, data
);
344 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
345 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
346 dismissDialog(DIALOG_NO_ACCOUNT
);
347 if (resultCode
== RESULT_CANCELED
) {
350 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
351 if (accounts
.length
== 0) {
352 showDialog(DIALOG_NO_ACCOUNT
);
354 // there is no need for checking for is there more then one
355 // account at this point
356 // since account setup can set only one account at time
357 setAccount(accounts
[0]);
358 populateDirectoryList();
363 private void populateDirectoryList() {
364 setContentView(R
.layout
.uploader_layout
);
366 ListView mListView
= (ListView
) findViewById(android
.R
.id
.list
);
368 String current_dir
= mParents
.peek();
369 if(current_dir
.equals("")){
370 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
373 getSupportActionBar().setTitle(current_dir
);
375 boolean notRoot
= (mParents
.size() > 1);
376 ActionBar actionBar
= getSupportActionBar();
377 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
378 actionBar
.setHomeButtonEnabled(notRoot
);
380 String full_path
= generatePath(mParents
);
382 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
384 mFile
= getStorageManager().getFileByPath(full_path
);
386 Vector
<OCFile
> files
= getStorageManager().getFolderContent(mFile
);
387 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
388 for (OCFile f
: files
) {
389 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
391 h
.put("dirname", f
.getFileName());
395 SimpleAdapter sa
= new SimpleAdapter(this,
397 R
.layout
.uploader_list_item_layout
,
398 new String
[] {"dirname"},
399 new int[] {R
.id
.textView1
});
401 mListView
.setAdapter(sa
);
402 Button btnChooseFolder
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
403 btnChooseFolder
.setOnClickListener(this);
405 Button btnNewFolder
= (Button
) findViewById(R
.id
.uploader_new_folder
);
406 btnNewFolder
.setOnClickListener(this);
408 mListView
.setOnItemClickListener(this);
412 private String
generatePath(Stack
<String
> dirs
) {
413 String full_path
= "";
415 for (String a
: dirs
)
416 full_path
+= a
+ "/";
420 private void prepareStreamsToUpload() {
421 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
422 mStreamsToUpload
= new ArrayList
<Parcelable
>();
423 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
424 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
425 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
429 private boolean somethingToUpload() {
430 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
433 public void uploadFiles() {
436 ArrayList
<String
> local
= new ArrayList
<String
>();
437 ArrayList
<String
> remote
= new ArrayList
<String
>();
439 // this checks the mimeType
440 for (Parcelable mStream
: mStreamsToUpload
) {
442 Uri uri
= (Uri
) mStream
;
444 if (uri
.getScheme().equals("content")) {
446 String mimeType
= getContentResolver().getType(uri
);
448 if (mimeType
.contains("image")) {
449 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
,
450 Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
,
452 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
455 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
456 String data
= c
.getString(index
);
457 String filePath
= mUploadPath
+
458 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
));
461 CopyTmpFileAsyncTask copyTask
= new CopyTmpFileAsyncTask(this);
462 Object
[] params
= { uri
, filePath
};
464 data
= copyTask
.execute(params
).get();
465 } catch (ExecutionException e
) {
466 Log_OC
.e(TAG
, "ExecutionException " + e
);
467 } catch (InterruptedException e
) {
468 Log_OC
.e(TAG
, "InterruptedException " + e
);
473 remote
.add(mUploadPath
+
474 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
477 else if (mimeType
.contains("video")) {
478 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
,
479 Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
,
480 Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
481 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
484 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
485 String data
= c
.getString(index
);
487 remote
.add(mUploadPath
+
488 c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
491 else if (mimeType
.contains("audio")) {
492 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
,
493 Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
,
495 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
498 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
499 String data
= c
.getString(index
);
501 remote
.add(mUploadPath
+
502 c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
506 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
508 // cut everything whats before mnt. It occurred to me that sometimes
509 // apps send their name into the URI
510 if (filePath
.contains("mnt")) {
511 String splitedFilePath
[] = filePath
.split("/mnt");
512 filePath
= splitedFilePath
[1];
514 final File file
= new File(filePath
);
515 local
.add(file
.getAbsolutePath());
516 remote
.add(mUploadPath
+ file
.getName());
519 } else if (uri
.getScheme().equals("file")) {
520 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
522 if (filePath
.contains("mnt")) {
523 String splitedFilePath
[] = filePath
.split("/mnt");
524 filePath
= splitedFilePath
[1];
526 final File file
= new File(filePath
);
527 local
.add(file
.getAbsolutePath());
528 remote
.add(mUploadPath
+ file
.getName());
531 throw new SecurityException();
535 throw new SecurityException();
538 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
539 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
540 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
541 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
,
542 remote
.toArray(new String
[remote
.size()]));
543 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
544 startService(intent
);
546 //Save the path to shared preferences
547 SharedPreferences
.Editor appPrefs
= PreferenceManager
548 .getDefaultSharedPreferences(getApplicationContext()).edit();
549 appPrefs
.putString("last_upload_path", mUploadPath
);
555 } catch (SecurityException e
) {
556 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
),
557 getString(R
.string
.app_name
));
558 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
563 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
564 super.onRemoteOperationFinish(operation
, result
);
567 if (operation
instanceof CreateFolderOperation
) {
568 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
574 * Updates the view associated to the activity after the finish of an operation
575 * trying create a new folder
577 * @param operation Creation operation performed.
578 * @param result Result of the creation.
580 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
581 RemoteOperationResult result
) {
582 if (result
.isSuccess()) {
583 dismissLoadingDialog();
584 populateDirectoryList();
586 dismissLoadingDialog();
588 Toast msg
= Toast
.makeText(this,
589 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
593 } catch (NotFoundException e
) {
594 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
601 * Loads the target folder initialize shown to the user.
603 * The target account has to be chosen before this method is called.
605 private void initTargetFolder() {
606 if (getStorageManager() == null
) {
607 throw new IllegalStateException("Do not call this method before " +
608 "initializing mStorageManager");
611 SharedPreferences appPreferences
= PreferenceManager
612 .getDefaultSharedPreferences(getApplicationContext());
614 String last_path
= appPreferences
.getString("last_upload_path", "");
615 // "/" equals root-directory
616 if(last_path
.equals("/")) {
619 String
[] dir_names
= last_path
.split("/");
620 for (String dir
: dir_names
)
623 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
624 while(!getStorageManager().fileExists(generatePath(mParents
)) && mParents
.size() > 1){
631 public boolean onOptionsItemSelected(MenuItem item
) {
632 boolean retval
= true
;
633 switch (item
.getItemId()) {
634 case android
.R
.id
.home
:
635 if((mParents
.size() > 1)) {
641 retval
= super.onOptionsItemSelected(item
);
648 * Process the result of CopyTmpFileAsyncTask
652 public void OnCopyTmpFileTaskListener(String result
) {