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
.util
.ArrayList
;
26 import java
.util
.HashMap
;
27 import java
.util
.LinkedList
;
28 import java
.util
.List
;
29 import java
.util
.Stack
;
30 import java
.util
.Vector
;
32 import android
.accounts
.Account
;
33 import android
.accounts
.AccountManager
;
34 import android
.app
.AlertDialog
;
35 import android
.app
.AlertDialog
.Builder
;
36 import android
.app
.Dialog
;
37 import android
.app
.ProgressDialog
;
38 import android
.content
.Context
;
39 import android
.content
.DialogInterface
;
40 import android
.content
.DialogInterface
.OnCancelListener
;
41 import android
.content
.DialogInterface
.OnClickListener
;
42 import android
.content
.Intent
;
43 import android
.content
.SharedPreferences
;
44 import android
.content
.res
.Resources
.NotFoundException
;
45 import android
.database
.Cursor
;
46 import android
.net
.Uri
;
47 import android
.os
.Bundle
;
48 import android
.os
.Parcelable
;
49 import android
.preference
.PreferenceManager
;
50 import android
.provider
.MediaStore
.Audio
;
51 import android
.provider
.MediaStore
.Images
;
52 import android
.provider
.MediaStore
.Video
;
53 import android
.view
.View
;
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
.ListView
;
59 import android
.widget
.SimpleAdapter
;
60 import android
.widget
.Toast
;
62 import com
.actionbarsherlock
.app
.ActionBar
;
63 import com
.actionbarsherlock
.view
.MenuItem
;
64 import com
.owncloud
.android
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
67 import com
.owncloud
.android
.datamodel
.OCFile
;
68 import com
.owncloud
.android
.files
.services
.FileUploader
;
69 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
70 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
71 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
72 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
73 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
74 import com
.owncloud
.android
.utils
.DisplayUtils
;
75 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
79 * This can be used to upload things to an ownCloud instance.
81 public class Uploader
extends FileActivity
82 implements OnItemClickListener
, android
.view
.View
.OnClickListener
{
84 private static final String TAG
= Uploader
.class.getSimpleName();
86 //private Account mAccount;
87 private AccountManager mAccountManager
;
88 private Stack
<String
> mParents
;
89 private ArrayList
<Parcelable
> mStreamsToUpload
;
90 private boolean mCreateDir
;
91 private String mUploadPath
;
92 //private FileDataStorageManager mStorageManager;
94 private boolean mAccountSelected
;
96 private final static int DIALOG_NO_ACCOUNT
= 0;
97 private final static int DIALOG_WAITING
= 1;
98 private final static int DIALOG_NO_STREAM
= 2;
99 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
101 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
103 private final static String KEY_PARENTS
= "PARENTS";
104 private final static String KEY_ACCOUNT
= "ACCOUNT";
105 private final static String KEY_FILE
= "FILE";
106 private final static String KEY_ACCOUNT_SELECTED
= "ACCOUNT_SELECTED";
109 protected void onCreate(Bundle savedInstanceState
) {
110 prepareStreamsToUpload();
112 if (savedInstanceState
== null
) {
113 mParents
= new Stack
<String
>();
114 mAccountSelected
= false
;
116 mParents
= (Stack
<String
>) savedInstanceState
.getSerializable(KEY_PARENTS
);
117 // mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
118 mFile
= savedInstanceState
.getParcelable(KEY_FILE
);
119 // mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
120 mAccountSelected
= savedInstanceState
.getBoolean(KEY_ACCOUNT_SELECTED
);
122 super.onCreate(savedInstanceState
);
124 ActionBar actionBar
= getSupportActionBar();
125 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
128 // if (somethingToUpload()) {
129 // mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
130 // Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType());
131 // if (accounts.length == 0) {
132 // Log_OC.i(TAG, "No ownCloud account is available");
133 // showDialog(DIALOG_NO_ACCOUNT);
134 // } else if (accounts.length > 1 && !mAccountSelected) {
135 // Log_OC.i(TAG, "More than one ownCloud is available");
136 // showDialog(DIALOG_MULTIPLE_ACCOUNT);
138 // if (savedInstanceState == null) {
139 // mAccount = accounts[0];
140 // mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
142 // initTargetFolder();
143 // populateDirectoryList();
148 // showDialog(DIALOG_NO_STREAM);
154 protected void setAccount(Account account
, boolean savedAccount
) {
155 if (somethingToUpload()) {
156 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
157 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAccountType());
158 if (accounts
.length
== 0) {
159 Log_OC
.i(TAG
, "No ownCloud account is available");
160 showDialog(DIALOG_NO_ACCOUNT
);
161 } else if (accounts
.length
> 1 && !mAccountSelected
) {
162 Log_OC
.i(TAG
, "More than one ownCloud is available");
163 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
166 //mAccount = accounts[0];
167 //mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
168 setAccount(accounts
[0]);
170 // Part in onAccountSet
171 // initTargetFolder();
172 // populateDirectoryList();
177 showDialog(DIALOG_NO_STREAM
);
180 super.setAccount(account
, savedAccount
);
182 // Account oldAccount = mAccount;
183 // boolean validAccount = (account != null &&
184 // AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
185 // if (validAccount) {
186 // mAccount = account;
187 // mAccountWasSet = true;
188 // mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
191 // swapToDefaultAccount();
196 protected void onAccountSet(boolean stateWasRecovered
) {
197 super.onAccountSet(mAccountWasRestored
);
199 populateDirectoryList();
200 // if (getAccount() != null) {
201 // mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
204 // Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
209 protected void onSaveInstanceState(Bundle outState
) {
210 Log_OC
.d(TAG
, "onSaveInstanceState() start");
211 super.onSaveInstanceState(outState
);
212 outState
.putSerializable(KEY_PARENTS
, mParents
);
213 //outState.putParcelable(KEY_ACCOUNT, mAccount);
214 outState
.putParcelable(KEY_FILE
, mFile
);
215 outState
.putBoolean(KEY_ACCOUNT_SELECTED
, mAccountSelected
);
217 Log_OC
.d(TAG
, "onSaveInstanceState() end");
221 protected Dialog
onCreateDialog(final int id
) {
222 final AlertDialog
.Builder builder
= new Builder(this);
225 ProgressDialog pDialog
= new ProgressDialog(this);
226 pDialog
.setIndeterminate(false
);
227 pDialog
.setCancelable(false
);
228 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
230 case DIALOG_NO_ACCOUNT
:
231 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
232 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
233 builder
.setMessage(String
.format(
234 getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
235 builder
.setCancelable(false
);
236 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
238 public void onClick(DialogInterface dialog
, int which
) {
239 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
240 // using string value since in API7 this
241 // constatn is not defined
242 // in API7 < this constatant is defined in
243 // Settings.ADD_ACCOUNT_SETTINGS
244 // and Settings.EXTRA_AUTHORITIES
245 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
246 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
247 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
249 // since in API7 there is no direct call for
250 // account setup, so we need to
251 // show our own AccountSetupAcricity, get
252 // desired results and setup
253 // everything for ourself
254 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
255 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
259 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
261 public void onClick(DialogInterface dialog
, int which
) {
265 return builder
.create();
266 case DIALOG_MULTIPLE_ACCOUNT
:
267 CharSequence ac
[] = new CharSequence
[
268 mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
269 for (int i
= 0; i
< ac
.length
; ++i
) {
270 ac
[i
] = DisplayUtils
.convertIdn(
271 mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
273 builder
.setTitle(R
.string
.common_choose_account
);
274 builder
.setItems(ac
, new OnClickListener() {
276 public void onClick(DialogInterface dialog
, int which
) {
277 setAccount(mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
]);
278 onAccountSet(mAccountWasRestored
);
279 // mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
280 // initTargetFolder();
281 // populateDirectoryList();
283 mAccountSelected
= true
;
286 builder
.setCancelable(true
);
287 builder
.setOnCancelListener(new OnCancelListener() {
289 public void onCancel(DialogInterface dialog
) {
294 return builder
.create();
295 case DIALOG_NO_STREAM
:
296 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
297 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
298 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
299 builder
.setCancelable(false
);
300 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
302 public void onClick(DialogInterface dialog
, int which
) {
306 return builder
.create();
308 throw new IllegalArgumentException("Unknown dialog id: " + id
);
312 class a
implements OnClickListener
{
316 public a(String path
, EditText dirname
) {
322 public void onClick(DialogInterface dialog
, int which
) {
323 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
324 Uploader
.this.mCreateDir
= true
;
330 public void onBackPressed() {
332 if (mParents
.size() <= 1) {
333 super.onBackPressed();
337 populateDirectoryList();
342 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
343 // click on folder in the list
344 Log_OC
.d(TAG
, "on item click");
345 Vector
<OCFile
> tmpfiles
= getStorageManager().getFolderContent(mFile
);
346 if (tmpfiles
.size() <= 0) return;
348 Vector
<OCFile
> files
= new Vector
<OCFile
>();
349 for (OCFile f
: tmpfiles
)
352 if (files
.size() < position
) {
353 throw new IndexOutOfBoundsException("Incorrect item selected");
355 mParents
.push(files
.get(position
).getFileName());
356 populateDirectoryList();
360 public void onClick(View v
) {
363 case R
.id
.uploader_choose_folder
:
364 mUploadPath
= ""; // first element in mParents is root dir, represented by "";
365 // init mUploadPath with "/" results in a "//" prefix
366 for (String p
: mParents
)
367 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
368 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
374 case R
.id
.uploader_new_folder
:
375 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(mFile
);
376 dialog
.show(getSupportFragmentManager(), "createdirdialog");
381 throw new IllegalArgumentException("Wrong element clicked");
386 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
387 super.onActivityResult(requestCode
, resultCode
, data
);
388 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
389 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
390 dismissDialog(DIALOG_NO_ACCOUNT
);
391 if (resultCode
== RESULT_CANCELED
) {
394 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
395 if (accounts
.length
== 0) {
396 showDialog(DIALOG_NO_ACCOUNT
);
398 // there is no need for checking for is there more then one
399 // account at this point
400 // since account setup can set only one account at time
401 setAccount(accounts
[0]);
402 populateDirectoryList();
407 private void populateDirectoryList() {
408 setContentView(R
.layout
.uploader_layout
);
410 ListView mListView
= (ListView
) findViewById(android
.R
.id
.list
);
412 String current_dir
= mParents
.peek();
413 if(current_dir
.equals("")){
414 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
417 getSupportActionBar().setTitle(current_dir
);
419 boolean notRoot
= (mParents
.size() > 1);
420 ActionBar actionBar
= getSupportActionBar();
421 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
422 actionBar
.setHomeButtonEnabled(notRoot
);
424 String full_path
= generatePath(mParents
);
426 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
428 mFile
= getStorageManager().getFileByPath(full_path
);
430 Vector
<OCFile
> files
= getStorageManager().getFolderContent(mFile
);
431 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
432 for (OCFile f
: files
) {
433 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
435 h
.put("dirname", f
.getFileName());
439 SimpleAdapter sa
= new SimpleAdapter(this,
441 R
.layout
.uploader_list_item_layout
,
442 new String
[] {"dirname"},
443 new int[] {R
.id
.textView1
});
445 mListView
.setAdapter(sa
);
446 Button btnChooseFolder
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
447 btnChooseFolder
.setOnClickListener(this);
449 Button btnNewFolder
= (Button
) findViewById(R
.id
.uploader_new_folder
);
450 btnNewFolder
.setOnClickListener(this);
452 mListView
.setOnItemClickListener(this);
456 private String
generatePath(Stack
<String
> dirs
) {
457 String full_path
= "";
459 for (String a
: dirs
)
460 full_path
+= a
+ "/";
464 private void prepareStreamsToUpload() {
465 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
466 mStreamsToUpload
= new ArrayList
<Parcelable
>();
467 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
468 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
469 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
473 private boolean somethingToUpload() {
474 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
477 public void uploadFiles() {
480 ArrayList
<String
> local
= new ArrayList
<String
>();
481 ArrayList
<String
> remote
= new ArrayList
<String
>();
483 // this checks the mimeType
484 for (Parcelable mStream
: mStreamsToUpload
) {
486 Uri uri
= (Uri
) mStream
;
488 if (uri
.getScheme().equals("content")) {
490 String mimeType
= getContentResolver().getType(uri
);
492 if (mimeType
.contains("image")) {
493 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
,
494 Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
,
496 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
499 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
500 String data
= c
.getString(index
);
502 remote
.add(mUploadPath
+
503 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
506 else if (mimeType
.contains("video")) {
507 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
,
508 Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
,
509 Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
510 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
513 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
514 String data
= c
.getString(index
);
516 remote
.add(mUploadPath
+
517 c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
520 else if (mimeType
.contains("audio")) {
521 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
,
522 Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
,
524 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
527 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
528 String data
= c
.getString(index
);
530 remote
.add(mUploadPath
+
531 c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
535 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
537 // cut everything whats before mnt. It occurred to me that sometimes
538 // apps send their name into the URI
539 if (filePath
.contains("mnt")) {
540 String splitedFilePath
[] = filePath
.split("/mnt");
541 filePath
= splitedFilePath
[1];
543 final File file
= new File(filePath
);
544 local
.add(file
.getAbsolutePath());
545 remote
.add(mUploadPath
+ file
.getName());
548 } else if (uri
.getScheme().equals("file")) {
549 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
551 if (filePath
.contains("mnt")) {
552 String splitedFilePath
[] = filePath
.split("/mnt");
553 filePath
= splitedFilePath
[1];
555 final File file
= new File(filePath
);
556 local
.add(file
.getAbsolutePath());
557 remote
.add(mUploadPath
+ file
.getName());
560 throw new SecurityException();
564 throw new SecurityException();
567 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
568 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
569 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
570 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
,
571 remote
.toArray(new String
[remote
.size()]));
572 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
573 startService(intent
);
575 //Save the path to shared preferences
576 SharedPreferences
.Editor appPrefs
= PreferenceManager
577 .getDefaultSharedPreferences(getApplicationContext()).edit();
578 appPrefs
.putString("last_upload_path", mUploadPath
);
584 } catch (SecurityException e
) {
585 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
),
586 getString(R
.string
.app_name
));
587 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
592 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
593 super.onRemoteOperationFinish(operation
, result
);
596 if (operation
instanceof CreateFolderOperation
) {
597 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
603 * Updates the view associated to the activity after the finish of an operation
604 * trying create a new folder
606 * @param operation Creation operation performed.
607 * @param result Result of the creation.
609 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
610 RemoteOperationResult result
) {
611 if (result
.isSuccess()) {
612 dismissLoadingDialog();
613 populateDirectoryList();
615 dismissLoadingDialog();
617 Toast msg
= Toast
.makeText(this,
618 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
622 } catch (NotFoundException e
) {
623 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
630 * Loads the target folder initialize shown to the user.
632 * The target account has to be chosen before this method is called.
634 private void initTargetFolder() {
635 if (getStorageManager() == null
) {
636 throw new IllegalStateException("Do not call this method before " +
637 "initializing mStorageManager");
640 SharedPreferences appPreferences
= PreferenceManager
641 .getDefaultSharedPreferences(getApplicationContext());
643 String last_path
= appPreferences
.getString("last_upload_path", "");
644 // "/" equals root-directory
645 if(last_path
.equals("/")) {
649 String
[] dir_names
= last_path
.split("/");
650 for (String dir
: dir_names
)
653 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
654 while(!getStorageManager().fileExists(generatePath(mParents
)) && mParents
.size() > 1){
661 public boolean onOptionsItemSelected(MenuItem item
) {
662 boolean retval
= true
;
663 switch (item
.getItemId()) {
664 case android
.R
.id
.home
: {
665 if((mParents
.size() > 1)) {
671 retval
= super.onOptionsItemSelected(item
);