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
;
38 import android
.accounts
.Account
;
39 import android
.accounts
.AccountManager
;
40 import android
.app
.AlertDialog
;
41 import android
.app
.AlertDialog
.Builder
;
42 import android
.app
.Dialog
;
43 import android
.app
.ProgressDialog
;
44 import android
.content
.Context
;
45 import android
.content
.DialogInterface
;
46 import android
.content
.DialogInterface
.OnCancelListener
;
47 import android
.content
.DialogInterface
.OnClickListener
;
48 import android
.content
.Intent
;
49 import android
.content
.SharedPreferences
;
50 import android
.content
.res
.Resources
.NotFoundException
;
51 import android
.database
.Cursor
;
52 import android
.net
.Uri
;
53 import android
.os
.Bundle
;
54 import android
.os
.ParcelFileDescriptor
;
55 import android
.os
.Parcelable
;
56 import android
.preference
.PreferenceManager
;
57 import android
.provider
.MediaStore
.Audio
;
58 import android
.provider
.MediaStore
.Images
;
59 import android
.provider
.MediaStore
.Video
;
60 import android
.view
.View
;
61 import android
.widget
.AdapterView
;
62 import android
.widget
.AdapterView
.OnItemClickListener
;
63 import android
.widget
.Button
;
64 import android
.widget
.EditText
;
65 import android
.widget
.ListView
;
66 import android
.widget
.SimpleAdapter
;
67 import android
.widget
.Toast
;
69 import com
.actionbarsherlock
.app
.ActionBar
;
70 import com
.actionbarsherlock
.view
.MenuItem
;
71 import com
.owncloud
.android
.MainApp
;
72 import com
.owncloud
.android
.R
;
73 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
74 import com
.owncloud
.android
.datamodel
.OCFile
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
79 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
80 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
81 import com
.owncloud
.android
.utils
.DisplayUtils
;
82 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
83 import com
.owncloud
.android
.utils
.FileStorageUtils
;
84 import com
.owncloud
.android
.utils
.UriUtils
;
88 * This can be used to upload things to an ownCloud instance.
90 public class Uploader
extends FileActivity
91 implements OnItemClickListener
, android
.view
.View
.OnClickListener
{
93 private static final String TAG
= Uploader
.class.getSimpleName();
95 private AccountManager mAccountManager
;
96 private Stack
<String
> mParents
;
97 private ArrayList
<Parcelable
> mStreamsToUpload
;
98 private boolean mCreateDir
;
99 private String mUploadPath
;
100 private OCFile mFile
;
101 private boolean mAccountSelected
;
103 private final static int DIALOG_NO_ACCOUNT
= 0;
104 private final static int DIALOG_WAITING
= 1;
105 private final static int DIALOG_NO_STREAM
= 2;
106 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
108 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
110 private final static String KEY_PARENTS
= "PARENTS";
111 private final static String KEY_FILE
= "FILE";
112 private final static String KEY_ACCOUNT_SELECTED
= "ACCOUNT_SELECTED";
115 protected void onCreate(Bundle savedInstanceState
) {
116 prepareStreamsToUpload();
118 if (savedInstanceState
== null
) {
119 mParents
= new Stack
<String
>();
120 mAccountSelected
= false
;
122 mParents
= (Stack
<String
>) savedInstanceState
.getSerializable(KEY_PARENTS
);
123 mFile
= savedInstanceState
.getParcelable(KEY_FILE
);
124 mAccountSelected
= savedInstanceState
.getBoolean(KEY_ACCOUNT_SELECTED
);
126 super.onCreate(savedInstanceState
);
128 ActionBar actionBar
= getSupportActionBar();
129 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
134 protected void setAccount(Account account
, boolean savedAccount
) {
135 if (somethingToUpload()) {
136 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
137 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAccountType());
138 if (accounts
.length
== 0) {
139 Log_OC
.i(TAG
, "No ownCloud account is available");
140 showDialog(DIALOG_NO_ACCOUNT
);
141 } else if (accounts
.length
> 1 && !mAccountSelected
) {
142 Log_OC
.i(TAG
, "More than one ownCloud is available");
143 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
146 setAccount(accounts
[0]);
151 showDialog(DIALOG_NO_STREAM
);
154 super.setAccount(account
, savedAccount
);
158 protected void onAccountSet(boolean stateWasRecovered
) {
159 super.onAccountSet(mAccountWasRestored
);
161 populateDirectoryList();
165 protected void onSaveInstanceState(Bundle outState
) {
166 Log_OC
.d(TAG
, "onSaveInstanceState() start");
167 super.onSaveInstanceState(outState
);
168 outState
.putSerializable(KEY_PARENTS
, mParents
);
169 //outState.putParcelable(KEY_ACCOUNT, mAccount);
170 outState
.putParcelable(KEY_FILE
, mFile
);
171 outState
.putBoolean(KEY_ACCOUNT_SELECTED
, mAccountSelected
);
173 Log_OC
.d(TAG
, "onSaveInstanceState() end");
177 protected Dialog
onCreateDialog(final int id
) {
178 final AlertDialog
.Builder builder
= new Builder(this);
181 ProgressDialog pDialog
= new ProgressDialog(this);
182 pDialog
.setIndeterminate(false
);
183 pDialog
.setCancelable(false
);
184 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
186 case DIALOG_NO_ACCOUNT
:
187 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
188 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
189 builder
.setMessage(String
.format(
190 getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
191 builder
.setCancelable(false
);
192 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
194 public void onClick(DialogInterface dialog
, int which
) {
195 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
196 // using string value since in API7 this
197 // constatn is not defined
198 // in API7 < this constatant is defined in
199 // Settings.ADD_ACCOUNT_SETTINGS
200 // and Settings.EXTRA_AUTHORITIES
201 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
202 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
203 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
205 // since in API7 there is no direct call for
206 // account setup, so we need to
207 // show our own AccountSetupAcricity, get
208 // desired results and setup
209 // everything for ourself
210 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
211 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
215 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
217 public void onClick(DialogInterface dialog
, int which
) {
221 return builder
.create();
222 case DIALOG_MULTIPLE_ACCOUNT
:
223 CharSequence ac
[] = new CharSequence
[
224 mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
225 for (int i
= 0; i
< ac
.length
; ++i
) {
226 ac
[i
] = DisplayUtils
.convertIdn(
227 mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
229 builder
.setTitle(R
.string
.common_choose_account
);
230 builder
.setItems(ac
, new OnClickListener() {
232 public void onClick(DialogInterface dialog
, int which
) {
233 setAccount(mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
]);
234 onAccountSet(mAccountWasRestored
);
236 mAccountSelected
= true
;
239 builder
.setCancelable(true
);
240 builder
.setOnCancelListener(new OnCancelListener() {
242 public void onCancel(DialogInterface dialog
) {
247 return builder
.create();
248 case DIALOG_NO_STREAM
:
249 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
250 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
251 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
252 builder
.setCancelable(false
);
253 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
255 public void onClick(DialogInterface dialog
, int which
) {
259 return builder
.create();
261 throw new IllegalArgumentException("Unknown dialog id: " + id
);
265 class a
implements OnClickListener
{
269 public a(String path
, EditText dirname
) {
275 public void onClick(DialogInterface dialog
, int which
) {
276 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
277 Uploader
.this.mCreateDir
= true
;
283 public void onBackPressed() {
285 if (mParents
.size() <= 1) {
286 super.onBackPressed();
290 populateDirectoryList();
295 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
296 // click on folder in the list
297 Log_OC
.d(TAG
, "on item click");
298 Vector
<OCFile
> tmpfiles
= getStorageManager().getFolderContent(mFile
);
299 if (tmpfiles
.size() <= 0) return;
301 Vector
<OCFile
> files
= new Vector
<OCFile
>();
302 for (OCFile f
: tmpfiles
)
305 if (files
.size() < position
) {
306 throw new IndexOutOfBoundsException("Incorrect item selected");
308 mParents
.push(files
.get(position
).getFileName());
309 populateDirectoryList();
313 public void onClick(View v
) {
316 case R
.id
.uploader_choose_folder
:
317 mUploadPath
= ""; // first element in mParents is root dir, represented by "";
318 // init mUploadPath with "/" results in a "//" prefix
319 for (String p
: mParents
)
320 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
321 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
327 case R
.id
.uploader_new_folder
:
328 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(mFile
);
329 dialog
.show(getSupportFragmentManager(), "createdirdialog");
334 throw new IllegalArgumentException("Wrong element clicked");
339 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
340 super.onActivityResult(requestCode
, resultCode
, data
);
341 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
342 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
343 dismissDialog(DIALOG_NO_ACCOUNT
);
344 if (resultCode
== RESULT_CANCELED
) {
347 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
348 if (accounts
.length
== 0) {
349 showDialog(DIALOG_NO_ACCOUNT
);
351 // there is no need for checking for is there more then one
352 // account at this point
353 // since account setup can set only one account at time
354 setAccount(accounts
[0]);
355 populateDirectoryList();
360 private void populateDirectoryList() {
361 setContentView(R
.layout
.uploader_layout
);
363 ListView mListView
= (ListView
) findViewById(android
.R
.id
.list
);
365 String current_dir
= mParents
.peek();
366 if(current_dir
.equals("")){
367 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
370 getSupportActionBar().setTitle(current_dir
);
372 boolean notRoot
= (mParents
.size() > 1);
373 ActionBar actionBar
= getSupportActionBar();
374 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
375 actionBar
.setHomeButtonEnabled(notRoot
);
377 String full_path
= generatePath(mParents
);
379 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
381 mFile
= getStorageManager().getFileByPath(full_path
);
383 Vector
<OCFile
> files
= getStorageManager().getFolderContent(mFile
);
384 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
385 for (OCFile f
: files
) {
386 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
388 h
.put("dirname", f
.getFileName());
392 SimpleAdapter sa
= new SimpleAdapter(this,
394 R
.layout
.uploader_list_item_layout
,
395 new String
[] {"dirname"},
396 new int[] {R
.id
.textView1
});
398 mListView
.setAdapter(sa
);
399 Button btnChooseFolder
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
400 btnChooseFolder
.setOnClickListener(this);
402 Button btnNewFolder
= (Button
) findViewById(R
.id
.uploader_new_folder
);
403 btnNewFolder
.setOnClickListener(this);
405 mListView
.setOnItemClickListener(this);
409 private String
generatePath(Stack
<String
> dirs
) {
410 String full_path
= "";
412 for (String a
: dirs
)
413 full_path
+= a
+ "/";
417 private void prepareStreamsToUpload() {
418 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
419 mStreamsToUpload
= new ArrayList
<Parcelable
>();
420 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
421 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
422 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
426 private boolean somethingToUpload() {
427 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
430 public void uploadFiles() {
433 ArrayList
<String
> local
= new ArrayList
<String
>();
434 ArrayList
<String
> remote
= new ArrayList
<String
>();
436 // this checks the mimeType
437 for (Parcelable mStream
: mStreamsToUpload
) {
439 Uri uri
= (Uri
) mStream
;
441 if (uri
.getScheme().equals("content")) {
443 String mimeType
= getContentResolver().getType(uri
);
445 if (mimeType
.contains("image")) {
446 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
,
447 Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
,
449 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
452 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
453 String data
= c
.getString(index
);
454 String filePath
= mUploadPath
+
455 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
));
456 String fullTempPath
= FileStorageUtils
.getTemporalPath(getAccount().name
)
458 InputStream inputStream
= null
;
459 FileOutputStream outputStream
= null
;
462 inputStream
= getContentResolver().openInputStream(uri
);
463 File cacheFile
= new File(fullTempPath
);
464 cacheFile
.createNewFile();
465 outputStream
= new FileOutputStream(fullTempPath
);
466 byte[] buffer
= new byte[4096];
470 while ((count
= inputStream
.read(buffer
)) > 0) {
471 outputStream
.write(buffer
, 0, count
);
474 outputStream
.close();
478 }catch (Exception e
) {
479 if (inputStream
!= null
) {
482 } catch (Exception e1
) {
487 if (outputStream
!= null
) {
489 outputStream
.close();
490 } catch (Exception e1
) {
495 if (fullTempPath
!= null
) {
496 File f
= new File(fullTempPath
);
503 remote
.add(mUploadPath
+
504 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
507 else if (mimeType
.contains("video")) {
508 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
,
509 Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
,
510 Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
511 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
514 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
515 String data
= c
.getString(index
);
517 remote
.add(mUploadPath
+
518 c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
521 else if (mimeType
.contains("audio")) {
522 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
,
523 Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
,
525 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
528 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
529 String data
= c
.getString(index
);
531 remote
.add(mUploadPath
+
532 c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
536 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
538 // cut everything whats before mnt. It occurred to me that sometimes
539 // apps send their name into the URI
540 if (filePath
.contains("mnt")) {
541 String splitedFilePath
[] = filePath
.split("/mnt");
542 filePath
= splitedFilePath
[1];
544 final File file
= new File(filePath
);
545 local
.add(file
.getAbsolutePath());
546 remote
.add(mUploadPath
+ file
.getName());
549 } else if (uri
.getScheme().equals("file")) {
550 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
552 if (filePath
.contains("mnt")) {
553 String splitedFilePath
[] = filePath
.split("/mnt");
554 filePath
= splitedFilePath
[1];
556 final File file
= new File(filePath
);
557 local
.add(file
.getAbsolutePath());
558 remote
.add(mUploadPath
+ file
.getName());
561 throw new SecurityException();
565 throw new SecurityException();
568 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
569 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
570 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
571 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
,
572 remote
.toArray(new String
[remote
.size()]));
573 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
574 startService(intent
);
576 //Save the path to shared preferences
577 SharedPreferences
.Editor appPrefs
= PreferenceManager
578 .getDefaultSharedPreferences(getApplicationContext()).edit();
579 appPrefs
.putString("last_upload_path", mUploadPath
);
585 } catch (SecurityException e
) {
586 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
),
587 getString(R
.string
.app_name
));
588 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
593 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
594 super.onRemoteOperationFinish(operation
, result
);
597 if (operation
instanceof CreateFolderOperation
) {
598 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
604 * Updates the view associated to the activity after the finish of an operation
605 * trying create a new folder
607 * @param operation Creation operation performed.
608 * @param result Result of the creation.
610 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
611 RemoteOperationResult result
) {
612 if (result
.isSuccess()) {
613 dismissLoadingDialog();
614 populateDirectoryList();
616 dismissLoadingDialog();
618 Toast msg
= Toast
.makeText(this,
619 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
623 } catch (NotFoundException e
) {
624 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
631 * Loads the target folder initialize shown to the user.
633 * The target account has to be chosen before this method is called.
635 private void initTargetFolder() {
636 if (getStorageManager() == null
) {
637 throw new IllegalStateException("Do not call this method before " +
638 "initializing mStorageManager");
641 SharedPreferences appPreferences
= PreferenceManager
642 .getDefaultSharedPreferences(getApplicationContext());
644 String last_path
= appPreferences
.getString("last_upload_path", "");
645 // "/" equals root-directory
646 if(last_path
.equals("/")) {
650 String
[] dir_names
= last_path
.split("/");
651 for (String dir
: dir_names
)
654 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
655 while(!getStorageManager().fileExists(generatePath(mParents
)) && mParents
.size() > 1){
662 public boolean onOptionsItemSelected(MenuItem item
) {
663 boolean retval
= true
;
664 switch (item
.getItemId()) {
665 case android
.R
.id
.home
: {
666 if((mParents
.size() > 1)) {
672 retval
= super.onOptionsItemSelected(item
);