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
.FileDataStorageManager
;
68 import com
.owncloud
.android
.datamodel
.OCFile
;
69 import com
.owncloud
.android
.files
.services
.FileUploader
;
70 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
72 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
73 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
74 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
75 import com
.owncloud
.android
.utils
.DisplayUtils
;
76 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
80 * This can be used to upload things to an ownCloud instance.
82 public class Uploader
extends FileActivity
83 implements OnItemClickListener
, android
.view
.View
.OnClickListener
{
85 private static final String TAG
= Uploader
.class.getSimpleName();
87 private Account mAccount
;
88 private AccountManager mAccountManager
;
89 private Stack
<String
> mParents
;
90 private ArrayList
<Parcelable
> mStreamsToUpload
;
91 private boolean mCreateDir
;
92 private String mUploadPath
;
93 private FileDataStorageManager mStorageManager
;
95 private boolean mAccountSelected
= false
;
97 private final static int DIALOG_NO_ACCOUNT
= 0;
98 private final static int DIALOG_WAITING
= 1;
99 private final static int DIALOG_NO_STREAM
= 2;
100 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
102 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
104 private final static String KEY_PARENTS
= "PARENTS";
105 private final static String KEY_ACCOUNT
= "ACCOUNT";
106 private final static String KEY_FILE
= "FILE";
107 private final static String KEY_ACCOUNT_SELECTED
= "ACCOUNT_SELECTED";
110 protected void onCreate(Bundle savedInstanceState
) {
111 super.onCreate(savedInstanceState
);
113 if (savedInstanceState
== null
) {
114 mParents
= new Stack
<String
>();
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
);
123 ActionBar actionBar
= getSupportActionBar();
124 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
126 if (prepareStreamsToUpload()) {
127 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
128 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAccountType());
129 if (accounts
.length
== 0) {
130 Log_OC
.i(TAG
, "No ownCloud account is available");
131 showDialog(DIALOG_NO_ACCOUNT
);
132 } else if (accounts
.length
> 1 && !mAccountSelected
) {
133 Log_OC
.i(TAG
, "More than one ownCloud is available");
134 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
136 mAccount
= accounts
[0];
137 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
139 populateDirectoryList();
144 showDialog(DIALOG_NO_STREAM
);
150 protected void onSaveInstanceState(Bundle outState
) {
151 Log_OC
.d(TAG
, "onSaveInstanceState() start");
152 super.onSaveInstanceState(outState
);
153 outState
.putSerializable(KEY_PARENTS
, mParents
);
154 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
155 outState
.putParcelable(KEY_FILE
, mFile
);
156 outState
.putBoolean(KEY_ACCOUNT_SELECTED
, mAccountSelected
);
158 Log_OC
.d(TAG
, "onSaveInstanceState() end");
162 protected Dialog
onCreateDialog(final int id
) {
163 final AlertDialog
.Builder builder
= new Builder(this);
166 ProgressDialog pDialog
= new ProgressDialog(this);
167 pDialog
.setIndeterminate(false
);
168 pDialog
.setCancelable(false
);
169 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
171 case DIALOG_NO_ACCOUNT
:
172 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
173 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
174 builder
.setMessage(String
.format(
175 getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
176 builder
.setCancelable(false
);
177 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
179 public void onClick(DialogInterface dialog
, int which
) {
180 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
181 // using string value since in API7 this
182 // constatn is not defined
183 // in API7 < this constatant is defined in
184 // Settings.ADD_ACCOUNT_SETTINGS
185 // and Settings.EXTRA_AUTHORITIES
186 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
187 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
188 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
190 // since in API7 there is no direct call for
191 // account setup, so we need to
192 // show our own AccountSetupAcricity, get
193 // desired results and setup
194 // everything for ourself
195 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
196 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
200 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
202 public void onClick(DialogInterface dialog
, int which
) {
206 return builder
.create();
207 case DIALOG_MULTIPLE_ACCOUNT
:
208 CharSequence ac
[] = new CharSequence
[
209 mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
210 for (int i
= 0; i
< ac
.length
; ++i
) {
211 ac
[i
] = DisplayUtils
.convertIdn(
212 mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
214 builder
.setTitle(R
.string
.common_choose_account
);
215 builder
.setItems(ac
, new OnClickListener() {
217 public void onClick(DialogInterface dialog
, int which
) {
218 mAccount
= mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
];
219 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
221 populateDirectoryList();
223 mAccountSelected
= true
;
226 builder
.setCancelable(true
);
227 builder
.setOnCancelListener(new OnCancelListener() {
229 public void onCancel(DialogInterface dialog
) {
234 return builder
.create();
235 case DIALOG_NO_STREAM
:
236 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
237 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
238 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
239 builder
.setCancelable(false
);
240 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
242 public void onClick(DialogInterface dialog
, int which
) {
246 return builder
.create();
248 throw new IllegalArgumentException("Unknown dialog id: " + id
);
252 class a
implements OnClickListener
{
256 public a(String path
, EditText dirname
) {
262 public void onClick(DialogInterface dialog
, int which
) {
263 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
264 Uploader
.this.mCreateDir
= true
;
270 public void onBackPressed() {
272 if (mParents
.size() <= 1) {
273 super.onBackPressed();
277 populateDirectoryList();
282 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
283 // click on folder in the list
284 Log_OC
.d(TAG
, "on item click");
285 Vector
<OCFile
> tmpfiles
= mStorageManager
.getFolderContent(mFile
);
286 if (tmpfiles
.size() <= 0) return;
288 Vector
<OCFile
> files
= new Vector
<OCFile
>();
289 for (OCFile f
: tmpfiles
)
292 if (files
.size() < position
) {
293 throw new IndexOutOfBoundsException("Incorrect item selected");
295 mParents
.push(files
.get(position
).getFileName());
296 populateDirectoryList();
300 public void onClick(View v
) {
303 case R
.id
.uploader_choose_folder
:
304 mUploadPath
= ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
305 for (String p
: mParents
)
306 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
307 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
313 case R
.id
.uploader_new_folder
:
314 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(mFile
);
315 dialog
.show(getSupportFragmentManager(), "createdirdialog");
320 throw new IllegalArgumentException("Wrong element clicked");
325 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
326 super.onActivityResult(requestCode
, resultCode
, data
);
327 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
328 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
329 dismissDialog(DIALOG_NO_ACCOUNT
);
330 if (resultCode
== RESULT_CANCELED
) {
333 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
334 if (accounts
.length
== 0) {
335 showDialog(DIALOG_NO_ACCOUNT
);
337 // there is no need for checking for is there more then one
338 // account at this point
339 // since account setup can set only one account at time
340 mAccount
= accounts
[0];
341 populateDirectoryList();
346 private void populateDirectoryList() {
347 setContentView(R
.layout
.uploader_layout
);
349 ListView mListView
= (ListView
) findViewById(android
.R
.id
.list
);
351 String current_dir
= mParents
.peek();
352 if(current_dir
.equals("")){
353 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
356 getSupportActionBar().setTitle(current_dir
);
358 boolean notRoot
= (mParents
.size() > 1);
359 ActionBar actionBar
= getSupportActionBar();
360 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
361 actionBar
.setHomeButtonEnabled(notRoot
);
363 String full_path
= generatePath(mParents
);
365 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
367 mFile
= mStorageManager
.getFileByPath(full_path
);
369 Vector
<OCFile
> files
= mStorageManager
.getFolderContent(mFile
);
370 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
371 for (OCFile f
: files
) {
372 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
374 h
.put("dirname", f
.getFileName());
378 SimpleAdapter sa
= new SimpleAdapter(this,
380 R
.layout
.uploader_list_item_layout
,
381 new String
[] {"dirname"},
382 new int[] {R
.id
.textView1
});
384 mListView
.setAdapter(sa
);
385 Button btnChooseFolder
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
386 btnChooseFolder
.setOnClickListener(this);
388 Button btnNewFolder
= (Button
) findViewById(R
.id
.uploader_new_folder
);
389 btnNewFolder
.setOnClickListener(this);
391 mListView
.setOnItemClickListener(this);
395 private String
generatePath(Stack
<String
> dirs
) {
396 String full_path
= "";
398 for (String a
: dirs
)
399 full_path
+= a
+ "/";
403 private boolean prepareStreamsToUpload() {
404 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
405 mStreamsToUpload
= new ArrayList
<Parcelable
>();
406 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
407 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
408 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
410 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
413 public void uploadFiles() {
416 ArrayList
<String
> local
= new ArrayList
<String
>();
417 ArrayList
<String
> remote
= new ArrayList
<String
>();
419 // this checks the mimeType
420 for (Parcelable mStream
: mStreamsToUpload
) {
422 Uri uri
= (Uri
) mStream
;
424 if (uri
.getScheme().equals("content")) {
426 String mimeType
= getContentResolver().getType(uri
);
428 if (mimeType
.contains("image")) {
429 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
,
430 Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
,
432 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
435 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
436 String data
= c
.getString(index
);
438 remote
.add(mUploadPath
+
439 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
442 else if (mimeType
.contains("video")) {
443 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
,
444 Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
,
445 Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
446 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
449 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
450 String data
= c
.getString(index
);
452 remote
.add(mUploadPath
+
453 c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
456 else if (mimeType
.contains("audio")) {
457 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
,
458 Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
,
460 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
463 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
464 String data
= c
.getString(index
);
466 remote
.add(mUploadPath
+
467 c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
471 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
473 // cut everything whats before mnt. It occurred to me that sometimes
474 // apps send their name into the URI
475 if (filePath
.contains("mnt")) {
476 String splitedFilePath
[] = filePath
.split("/mnt");
477 filePath
= splitedFilePath
[1];
479 final File file
= new File(filePath
);
480 local
.add(file
.getAbsolutePath());
481 remote
.add(mUploadPath
+ file
.getName());
484 } else if (uri
.getScheme().equals("file")) {
485 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
487 if (filePath
.contains("mnt")) {
488 String splitedFilePath
[] = filePath
.split("/mnt");
489 filePath
= splitedFilePath
[1];
491 final File file
= new File(filePath
);
492 local
.add(file
.getAbsolutePath());
493 remote
.add(mUploadPath
+ file
.getName());
496 throw new SecurityException();
500 throw new SecurityException();
503 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
504 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
505 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
506 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
,
507 remote
.toArray(new String
[remote
.size()]));
508 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, mAccount
);
509 startService(intent
);
511 //Save the path to shared preferences
512 SharedPreferences
.Editor appPrefs
= PreferenceManager
513 .getDefaultSharedPreferences(getApplicationContext()).edit();
514 appPrefs
.putString("last_upload_path", mUploadPath
);
520 } catch (SecurityException e
) {
521 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
),
522 getString(R
.string
.app_name
));
523 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
528 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
529 super.onRemoteOperationFinish(operation
, result
);
532 if (operation
instanceof CreateFolderOperation
) {
533 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
539 * Updates the view associated to the activity after the finish of an operation
540 * trying create a new folder
542 * @param operation Creation operation performed.
543 * @param result Result of the creation.
545 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
546 RemoteOperationResult result
) {
547 if (result
.isSuccess()) {
548 dismissLoadingDialog();
549 populateDirectoryList();
551 dismissLoadingDialog();
553 Toast msg
= Toast
.makeText(this,
554 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
558 } catch (NotFoundException e
) {
559 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
566 * Loads the target folder initialize shown to the user.
568 * The target account has to be chosen before this method is called.
570 private void initTargetFolder() {
571 if (mStorageManager
== null
) {
572 throw new IllegalStateException("Do not call this method before " +
573 "initializing mStorageManager");
576 SharedPreferences appPreferences
= PreferenceManager
577 .getDefaultSharedPreferences(getApplicationContext());
579 String last_path
= appPreferences
.getString("last_upload_path", "");
580 // "/" equals root-directory
581 if(last_path
.equals("/")) {
585 String
[] dir_names
= last_path
.split("/");
586 for (String dir
: dir_names
)
589 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
590 while(!mStorageManager
.fileExists(generatePath(mParents
)) && mParents
.size() > 1){
597 public boolean onOptionsItemSelected(MenuItem item
) {
598 boolean retval
= true
;
599 switch (item
.getItemId()) {
600 case android
.R
.id
.home
: {
601 if((mParents
.size() > 1)) {
607 retval
= super.onOptionsItemSelected(item
);