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
);
122 if (PinCheck
.checkIfPinEntry()){
123 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
124 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "ownCloudUploader");
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
);
455 remote
.add(mUploadPath
+
456 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
459 else if (mimeType
.contains("video")) {
460 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
,
461 Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
,
462 Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
463 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
466 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
467 String data
= c
.getString(index
);
469 remote
.add(mUploadPath
+
470 c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
473 else if (mimeType
.contains("audio")) {
474 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
,
475 Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
,
477 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
480 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
481 String data
= c
.getString(index
);
483 remote
.add(mUploadPath
+
484 c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
488 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
490 // cut everything whats before mnt. It occurred to me that sometimes
491 // apps send their name into the URI
492 if (filePath
.contains("mnt")) {
493 String splitedFilePath
[] = filePath
.split("/mnt");
494 filePath
= splitedFilePath
[1];
496 final File file
= new File(filePath
);
497 local
.add(file
.getAbsolutePath());
498 remote
.add(mUploadPath
+ file
.getName());
501 } else if (uri
.getScheme().equals("file")) {
502 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
504 if (filePath
.contains("mnt")) {
505 String splitedFilePath
[] = filePath
.split("/mnt");
506 filePath
= splitedFilePath
[1];
508 final File file
= new File(filePath
);
509 local
.add(file
.getAbsolutePath());
510 remote
.add(mUploadPath
+ file
.getName());
513 throw new SecurityException();
517 throw new SecurityException();
520 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
521 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
522 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
523 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
,
524 remote
.toArray(new String
[remote
.size()]));
525 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, getAccount());
526 startService(intent
);
528 //Save the path to shared preferences
529 SharedPreferences
.Editor appPrefs
= PreferenceManager
530 .getDefaultSharedPreferences(getApplicationContext()).edit();
531 appPrefs
.putString("last_upload_path", mUploadPath
);
537 } catch (SecurityException e
) {
538 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
),
539 getString(R
.string
.app_name
));
540 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
545 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
546 super.onRemoteOperationFinish(operation
, result
);
549 if (operation
instanceof CreateFolderOperation
) {
550 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
556 * Updates the view associated to the activity after the finish of an operation
557 * trying create a new folder
559 * @param operation Creation operation performed.
560 * @param result Result of the creation.
562 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
563 RemoteOperationResult result
) {
564 if (result
.isSuccess()) {
565 dismissLoadingDialog();
566 populateDirectoryList();
568 dismissLoadingDialog();
570 Toast msg
= Toast
.makeText(this,
571 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
575 } catch (NotFoundException e
) {
576 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
583 * Loads the target folder initialize shown to the user.
585 * The target account has to be chosen before this method is called.
587 private void initTargetFolder() {
588 if (getStorageManager() == null
) {
589 throw new IllegalStateException("Do not call this method before " +
590 "initializing mStorageManager");
593 SharedPreferences appPreferences
= PreferenceManager
594 .getDefaultSharedPreferences(getApplicationContext());
596 String last_path
= appPreferences
.getString("last_upload_path", "");
597 // "/" equals root-directory
598 if(last_path
.equals("/")) {
602 String
[] dir_names
= last_path
.split("/");
603 for (String dir
: dir_names
)
606 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
607 while(!getStorageManager().fileExists(generatePath(mParents
)) && mParents
.size() > 1){
614 public boolean onOptionsItemSelected(MenuItem item
) {
615 boolean retval
= true
;
616 switch (item
.getItemId()) {
617 case android
.R
.id
.home
: {
618 if((mParents
.size() > 1)) {
624 retval
= super.onOptionsItemSelected(item
);