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
.authentication
.PinCheck
;
68 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
69 import com
.owncloud
.android
.datamodel
.OCFile
;
70 import com
.owncloud
.android
.files
.services
.FileUploader
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
73 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
74 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
75 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
76 import com
.owncloud
.android
.utils
.DisplayUtils
;
77 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
81 * This can be used to upload things to an ownCloud instance.
83 public class Uploader
extends FileActivity
84 implements OnItemClickListener
, android
.view
.View
.OnClickListener
{
86 private static final String TAG
= Uploader
.class.getSimpleName();
88 private AccountManager mAccountManager
;
89 private Stack
<String
> mParents
;
90 private ArrayList
<Parcelable
> mStreamsToUpload
;
91 private boolean mCreateDir
;
92 private String mUploadPath
;
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_FILE
= "FILE";
105 private final static String KEY_ACCOUNT_SELECTED
= "ACCOUNT_SELECTED";
108 protected void onCreate(Bundle savedInstanceState
) {
109 prepareStreamsToUpload();
111 if (savedInstanceState
== null
) {
112 mParents
= new Stack
<String
>();
113 mAccountSelected
= false
;
115 mParents
= (Stack
<String
>) savedInstanceState
.getSerializable(KEY_PARENTS
);
116 mFile
= savedInstanceState
.getParcelable(KEY_FILE
);
117 mAccountSelected
= savedInstanceState
.getBoolean(KEY_ACCOUNT_SELECTED
);
119 super.onCreate(savedInstanceState
);
121 ActionBar actionBar
= getSupportActionBar();
122 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
127 protected void setAccount(Account account
, boolean savedAccount
) {
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
);
139 setAccount(accounts
[0]);
144 showDialog(DIALOG_NO_STREAM
);
147 super.setAccount(account
, savedAccount
);
151 protected void onAccountSet(boolean stateWasRecovered
) {
152 super.onAccountSet(mAccountWasRestored
);
154 populateDirectoryList();
158 protected void onSaveInstanceState(Bundle outState
) {
159 Log_OC
.d(TAG
, "onSaveInstanceState() start");
160 super.onSaveInstanceState(outState
);
161 outState
.putSerializable(KEY_PARENTS
, mParents
);
162 //outState.putParcelable(KEY_ACCOUNT, mAccount);
163 outState
.putParcelable(KEY_FILE
, mFile
);
164 outState
.putBoolean(KEY_ACCOUNT_SELECTED
, mAccountSelected
);
166 Log_OC
.d(TAG
, "onSaveInstanceState() end");
170 protected Dialog
onCreateDialog(final int id
) {
171 final AlertDialog
.Builder builder
= new Builder(this);
174 ProgressDialog pDialog
= new ProgressDialog(this);
175 pDialog
.setIndeterminate(false
);
176 pDialog
.setCancelable(false
);
177 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
179 case DIALOG_NO_ACCOUNT
:
180 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
181 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
182 builder
.setMessage(String
.format(
183 getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
184 builder
.setCancelable(false
);
185 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
187 public void onClick(DialogInterface dialog
, int which
) {
188 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
189 // using string value since in API7 this
190 // constatn is not defined
191 // in API7 < this constatant is defined in
192 // Settings.ADD_ACCOUNT_SETTINGS
193 // and Settings.EXTRA_AUTHORITIES
194 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
195 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
196 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
198 // since in API7 there is no direct call for
199 // account setup, so we need to
200 // show our own AccountSetupAcricity, get
201 // desired results and setup
202 // everything for ourself
203 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
204 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
208 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
210 public void onClick(DialogInterface dialog
, int which
) {
214 return builder
.create();
215 case DIALOG_MULTIPLE_ACCOUNT
:
216 CharSequence ac
[] = new CharSequence
[
217 mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
218 for (int i
= 0; i
< ac
.length
; ++i
) {
219 ac
[i
] = DisplayUtils
.convertIdn(
220 mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
222 builder
.setTitle(R
.string
.common_choose_account
);
223 builder
.setItems(ac
, new OnClickListener() {
225 public void onClick(DialogInterface dialog
, int which
) {
226 setAccount(mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
]);
227 onAccountSet(mAccountWasRestored
);
229 mAccountSelected
= true
;
232 builder
.setCancelable(true
);
233 builder
.setOnCancelListener(new OnCancelListener() {
235 public void onCancel(DialogInterface dialog
) {
240 return builder
.create();
241 case DIALOG_NO_STREAM
:
242 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
243 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
244 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
245 builder
.setCancelable(false
);
246 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
248 public void onClick(DialogInterface dialog
, int which
) {
252 return builder
.create();
254 throw new IllegalArgumentException("Unknown dialog id: " + id
);
258 class a
implements OnClickListener
{
262 public a(String path
, EditText dirname
) {
268 public void onClick(DialogInterface dialog
, int which
) {
269 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
270 Uploader
.this.mCreateDir
= true
;
276 public void onBackPressed() {
278 if (mParents
.size() <= 1) {
279 super.onBackPressed();
283 populateDirectoryList();
288 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
289 // click on folder in the list
290 Log_OC
.d(TAG
, "on item click");
291 Vector
<OCFile
> tmpfiles
= getStorageManager().getFolderContent(mFile
);
292 if (tmpfiles
.size() <= 0) return;
294 Vector
<OCFile
> files
= new Vector
<OCFile
>();
295 for (OCFile f
: tmpfiles
)
298 if (files
.size() < position
) {
299 throw new IndexOutOfBoundsException("Incorrect item selected");
301 mParents
.push(files
.get(position
).getFileName());
302 populateDirectoryList();
306 public void onClick(View v
) {
309 case R
.id
.uploader_choose_folder
:
310 mUploadPath
= ""; // first element in mParents is root dir, represented by "";
311 // init mUploadPath with "/" results in a "//" prefix
312 for (String p
: mParents
)
313 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
314 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
320 case R
.id
.uploader_new_folder
:
321 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(mFile
);
322 dialog
.show(getSupportFragmentManager(), "createdirdialog");
327 throw new IllegalArgumentException("Wrong element clicked");
332 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
333 super.onActivityResult(requestCode
, resultCode
, data
);
334 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
335 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
336 dismissDialog(DIALOG_NO_ACCOUNT
);
337 if (resultCode
== RESULT_CANCELED
) {
340 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
341 if (accounts
.length
== 0) {
342 showDialog(DIALOG_NO_ACCOUNT
);
344 // there is no need for checking for is there more then one
345 // account at this point
346 // since account setup can set only one account at time
347 setAccount(accounts
[0]);
348 populateDirectoryList();
353 private void populateDirectoryList() {
354 setContentView(R
.layout
.uploader_layout
);
356 ListView mListView
= (ListView
) findViewById(android
.R
.id
.list
);
358 String current_dir
= mParents
.peek();
359 if(current_dir
.equals("")){
360 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
363 getSupportActionBar().setTitle(current_dir
);
365 boolean notRoot
= (mParents
.size() > 1);
366 ActionBar actionBar
= getSupportActionBar();
367 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
368 actionBar
.setHomeButtonEnabled(notRoot
);
370 String full_path
= generatePath(mParents
);
372 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
374 mFile
= getStorageManager().getFileByPath(full_path
);
376 Vector
<OCFile
> files
= getStorageManager().getFolderContent(mFile
);
377 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
378 for (OCFile f
: files
) {
379 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
381 h
.put("dirname", f
.getFileName());
385 SimpleAdapter sa
= new SimpleAdapter(this,
387 R
.layout
.uploader_list_item_layout
,
388 new String
[] {"dirname"},
389 new int[] {R
.id
.textView1
});
391 mListView
.setAdapter(sa
);
392 Button btnChooseFolder
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
393 btnChooseFolder
.setOnClickListener(this);
395 Button btnNewFolder
= (Button
) findViewById(R
.id
.uploader_new_folder
);
396 btnNewFolder
.setOnClickListener(this);
398 mListView
.setOnItemClickListener(this);
402 private String
generatePath(Stack
<String
> dirs
) {
403 String full_path
= "";
405 for (String a
: dirs
)
406 full_path
+= a
+ "/";
410 private void prepareStreamsToUpload() {
411 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
412 mStreamsToUpload
= new ArrayList
<Parcelable
>();
413 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
414 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
415 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
419 private boolean somethingToUpload() {
420 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
423 public void uploadFiles() {
426 ArrayList
<String
> local
= new ArrayList
<String
>();
427 ArrayList
<String
> remote
= new ArrayList
<String
>();
429 // this checks the mimeType
430 for (Parcelable mStream
: mStreamsToUpload
) {
432 Uri uri
= (Uri
) mStream
;
434 if (uri
.getScheme().equals("content")) {
436 String mimeType
= getContentResolver().getType(uri
);
438 if (mimeType
.contains("image")) {
439 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
,
440 Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
,
442 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
445 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
446 String data
= c
.getString(index
);
448 remote
.add(mUploadPath
+
449 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
452 else if (mimeType
.contains("video")) {
453 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
,
454 Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
,
455 Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
456 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
459 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
460 String data
= c
.getString(index
);
462 remote
.add(mUploadPath
+
463 c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
466 else if (mimeType
.contains("audio")) {
467 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
,
468 Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
,
470 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
473 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
474 String data
= c
.getString(index
);
476 remote
.add(mUploadPath
+
477 c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
481 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
483 // cut everything whats before mnt. It occurred to me that sometimes
484 // apps send their name into the URI
485 if (filePath
.contains("mnt")) {
486 String splitedFilePath
[] = filePath
.split("/mnt");
487 filePath
= splitedFilePath
[1];
489 final File file
= new File(filePath
);
490 local
.add(file
.getAbsolutePath());
491 remote
.add(mUploadPath
+ file
.getName());
494 } else if (uri
.getScheme().equals("file")) {
495 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
497 if (filePath
.contains("mnt")) {
498 String splitedFilePath
[] = filePath
.split("/mnt");
499 filePath
= splitedFilePath
[1];
501 final File file
= new File(filePath
);
502 local
.add(file
.getAbsolutePath());
503 remote
.add(mUploadPath
+ file
.getName());
506 throw new SecurityException();
510 throw new SecurityException();
513 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
514 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
515 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
516 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
,
517 remote
.toArray(new String
[remote
.size()]));
518 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
519 startService(intent
);
521 //Save the path to shared preferences
522 SharedPreferences
.Editor appPrefs
= PreferenceManager
523 .getDefaultSharedPreferences(getApplicationContext()).edit();
524 appPrefs
.putString("last_upload_path", mUploadPath
);
530 } catch (SecurityException e
) {
531 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
),
532 getString(R
.string
.app_name
));
533 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
538 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
539 super.onRemoteOperationFinish(operation
, result
);
542 if (operation
instanceof CreateFolderOperation
) {
543 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
549 * Updates the view associated to the activity after the finish of an operation
550 * trying create a new folder
552 * @param operation Creation operation performed.
553 * @param result Result of the creation.
555 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
556 RemoteOperationResult result
) {
557 if (result
.isSuccess()) {
558 dismissLoadingDialog();
559 populateDirectoryList();
561 dismissLoadingDialog();
563 Toast msg
= Toast
.makeText(this,
564 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
568 } catch (NotFoundException e
) {
569 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
576 * Loads the target folder initialize shown to the user.
578 * The target account has to be chosen before this method is called.
580 private void initTargetFolder() {
581 if (getStorageManager() == null
) {
582 throw new IllegalStateException("Do not call this method before " +
583 "initializing mStorageManager");
586 SharedPreferences appPreferences
= PreferenceManager
587 .getDefaultSharedPreferences(getApplicationContext());
589 String last_path
= appPreferences
.getString("last_upload_path", "");
590 // "/" equals root-directory
591 if(last_path
.equals("/")) {
595 String
[] dir_names
= last_path
.split("/");
596 for (String dir
: dir_names
)
599 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
600 while(!getStorageManager().fileExists(generatePath(mParents
)) && mParents
.size() > 1){
607 public boolean onOptionsItemSelected(MenuItem item
) {
608 boolean retval
= true
;
609 switch (item
.getItemId()) {
610 case android
.R
.id
.home
: {
611 if((mParents
.size() > 1)) {
617 retval
= super.onOptionsItemSelected(item
);