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 if (savedInstanceState
== null
) {
137 mAccount
= accounts
[0];
138 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
141 populateDirectoryList();
146 showDialog(DIALOG_NO_STREAM
);
152 protected void onSaveInstanceState(Bundle outState
) {
153 Log_OC
.d(TAG
, "onSaveInstanceState() start");
154 super.onSaveInstanceState(outState
);
155 outState
.putSerializable(KEY_PARENTS
, mParents
);
156 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
157 outState
.putParcelable(KEY_FILE
, mFile
);
158 outState
.putBoolean(KEY_ACCOUNT_SELECTED
, mAccountSelected
);
160 Log_OC
.d(TAG
, "onSaveInstanceState() end");
164 protected Dialog
onCreateDialog(final int id
) {
165 final AlertDialog
.Builder builder
= new Builder(this);
168 ProgressDialog pDialog
= new ProgressDialog(this);
169 pDialog
.setIndeterminate(false
);
170 pDialog
.setCancelable(false
);
171 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
173 case DIALOG_NO_ACCOUNT
:
174 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
175 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
176 builder
.setMessage(String
.format(
177 getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
178 builder
.setCancelable(false
);
179 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
181 public void onClick(DialogInterface dialog
, int which
) {
182 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
183 // using string value since in API7 this
184 // constatn is not defined
185 // in API7 < this constatant is defined in
186 // Settings.ADD_ACCOUNT_SETTINGS
187 // and Settings.EXTRA_AUTHORITIES
188 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
189 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
190 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
192 // since in API7 there is no direct call for
193 // account setup, so we need to
194 // show our own AccountSetupAcricity, get
195 // desired results and setup
196 // everything for ourself
197 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
198 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
202 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
204 public void onClick(DialogInterface dialog
, int which
) {
208 return builder
.create();
209 case DIALOG_MULTIPLE_ACCOUNT
:
210 CharSequence ac
[] = new CharSequence
[
211 mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
212 for (int i
= 0; i
< ac
.length
; ++i
) {
213 ac
[i
] = DisplayUtils
.convertIdn(
214 mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
216 builder
.setTitle(R
.string
.common_choose_account
);
217 builder
.setItems(ac
, new OnClickListener() {
219 public void onClick(DialogInterface dialog
, int which
) {
220 mAccount
= mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
];
221 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
223 populateDirectoryList();
225 mAccountSelected
= true
;
228 builder
.setCancelable(true
);
229 builder
.setOnCancelListener(new OnCancelListener() {
231 public void onCancel(DialogInterface dialog
) {
236 return builder
.create();
237 case DIALOG_NO_STREAM
:
238 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
239 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
240 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
241 builder
.setCancelable(false
);
242 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
244 public void onClick(DialogInterface dialog
, int which
) {
248 return builder
.create();
250 throw new IllegalArgumentException("Unknown dialog id: " + id
);
254 class a
implements OnClickListener
{
258 public a(String path
, EditText dirname
) {
264 public void onClick(DialogInterface dialog
, int which
) {
265 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
266 Uploader
.this.mCreateDir
= true
;
272 public void onBackPressed() {
274 if (mParents
.size() <= 1) {
275 super.onBackPressed();
279 populateDirectoryList();
284 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
285 // click on folder in the list
286 Log_OC
.d(TAG
, "on item click");
287 Vector
<OCFile
> tmpfiles
= mStorageManager
.getFolderContent(mFile
);
288 if (tmpfiles
.size() <= 0) return;
290 Vector
<OCFile
> files
= new Vector
<OCFile
>();
291 for (OCFile f
: tmpfiles
)
294 if (files
.size() < position
) {
295 throw new IndexOutOfBoundsException("Incorrect item selected");
297 mParents
.push(files
.get(position
).getFileName());
298 populateDirectoryList();
302 public void onClick(View v
) {
305 case R
.id
.uploader_choose_folder
:
306 mUploadPath
= ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
307 for (String p
: mParents
)
308 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
309 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
315 case R
.id
.uploader_new_folder
:
316 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(mFile
);
317 dialog
.show(getSupportFragmentManager(), "createdirdialog");
322 throw new IllegalArgumentException("Wrong element clicked");
327 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
328 super.onActivityResult(requestCode
, resultCode
, data
);
329 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
330 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
331 dismissDialog(DIALOG_NO_ACCOUNT
);
332 if (resultCode
== RESULT_CANCELED
) {
335 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
336 if (accounts
.length
== 0) {
337 showDialog(DIALOG_NO_ACCOUNT
);
339 // there is no need for checking for is there more then one
340 // account at this point
341 // since account setup can set only one account at time
342 mAccount
= accounts
[0];
343 populateDirectoryList();
348 private void populateDirectoryList() {
349 setContentView(R
.layout
.uploader_layout
);
351 ListView mListView
= (ListView
) findViewById(android
.R
.id
.list
);
353 String current_dir
= mParents
.peek();
354 if(current_dir
.equals("")){
355 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
358 getSupportActionBar().setTitle(current_dir
);
360 boolean notRoot
= (mParents
.size() > 1);
361 ActionBar actionBar
= getSupportActionBar();
362 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
363 actionBar
.setHomeButtonEnabled(notRoot
);
365 String full_path
= generatePath(mParents
);
367 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
369 mFile
= mStorageManager
.getFileByPath(full_path
);
371 Vector
<OCFile
> files
= mStorageManager
.getFolderContent(mFile
);
372 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
373 for (OCFile f
: files
) {
374 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
376 h
.put("dirname", f
.getFileName());
380 SimpleAdapter sa
= new SimpleAdapter(this,
382 R
.layout
.uploader_list_item_layout
,
383 new String
[] {"dirname"},
384 new int[] {R
.id
.textView1
});
386 mListView
.setAdapter(sa
);
387 Button btnChooseFolder
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
388 btnChooseFolder
.setOnClickListener(this);
390 Button btnNewFolder
= (Button
) findViewById(R
.id
.uploader_new_folder
);
391 btnNewFolder
.setOnClickListener(this);
393 mListView
.setOnItemClickListener(this);
397 private String
generatePath(Stack
<String
> dirs
) {
398 String full_path
= "";
400 for (String a
: dirs
)
401 full_path
+= a
+ "/";
405 private boolean prepareStreamsToUpload() {
406 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
407 mStreamsToUpload
= new ArrayList
<Parcelable
>();
408 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
409 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
410 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
412 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
415 public void uploadFiles() {
418 ArrayList
<String
> local
= new ArrayList
<String
>();
419 ArrayList
<String
> remote
= new ArrayList
<String
>();
421 // this checks the mimeType
422 for (Parcelable mStream
: mStreamsToUpload
) {
424 Uri uri
= (Uri
) mStream
;
426 if (uri
.getScheme().equals("content")) {
428 String mimeType
= getContentResolver().getType(uri
);
430 if (mimeType
.contains("image")) {
431 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
,
432 Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
,
434 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
437 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
438 String data
= c
.getString(index
);
440 remote
.add(mUploadPath
+
441 c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
444 else if (mimeType
.contains("video")) {
445 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
,
446 Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
,
447 Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
448 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
451 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
452 String data
= c
.getString(index
);
454 remote
.add(mUploadPath
+
455 c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
458 else if (mimeType
.contains("audio")) {
459 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
,
460 Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
,
462 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
,
465 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
466 String data
= c
.getString(index
);
468 remote
.add(mUploadPath
+
469 c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
473 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
475 // cut everything whats before mnt. It occurred to me that sometimes
476 // apps send their name into the URI
477 if (filePath
.contains("mnt")) {
478 String splitedFilePath
[] = filePath
.split("/mnt");
479 filePath
= splitedFilePath
[1];
481 final File file
= new File(filePath
);
482 local
.add(file
.getAbsolutePath());
483 remote
.add(mUploadPath
+ file
.getName());
486 } else if (uri
.getScheme().equals("file")) {
487 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() +
489 if (filePath
.contains("mnt")) {
490 String splitedFilePath
[] = filePath
.split("/mnt");
491 filePath
= splitedFilePath
[1];
493 final File file
= new File(filePath
);
494 local
.add(file
.getAbsolutePath());
495 remote
.add(mUploadPath
+ file
.getName());
498 throw new SecurityException();
502 throw new SecurityException();
505 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
506 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
507 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
508 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
,
509 remote
.toArray(new String
[remote
.size()]));
510 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, mAccount
);
511 startService(intent
);
513 //Save the path to shared preferences
514 SharedPreferences
.Editor appPrefs
= PreferenceManager
515 .getDefaultSharedPreferences(getApplicationContext()).edit();
516 appPrefs
.putString("last_upload_path", mUploadPath
);
522 } catch (SecurityException e
) {
523 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
),
524 getString(R
.string
.app_name
));
525 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
530 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
531 super.onRemoteOperationFinish(operation
, result
);
534 if (operation
instanceof CreateFolderOperation
) {
535 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
541 * Updates the view associated to the activity after the finish of an operation
542 * trying create a new folder
544 * @param operation Creation operation performed.
545 * @param result Result of the creation.
547 private void onCreateFolderOperationFinish(CreateFolderOperation operation
,
548 RemoteOperationResult result
) {
549 if (result
.isSuccess()) {
550 dismissLoadingDialog();
551 populateDirectoryList();
553 dismissLoadingDialog();
555 Toast msg
= Toast
.makeText(this,
556 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
560 } catch (NotFoundException e
) {
561 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
568 * Loads the target folder initialize shown to the user.
570 * The target account has to be chosen before this method is called.
572 private void initTargetFolder() {
573 if (mStorageManager
== null
) {
574 throw new IllegalStateException("Do not call this method before " +
575 "initializing mStorageManager");
578 SharedPreferences appPreferences
= PreferenceManager
579 .getDefaultSharedPreferences(getApplicationContext());
581 String last_path
= appPreferences
.getString("last_upload_path", "");
582 // "/" equals root-directory
583 if(last_path
.equals("/")) {
587 String
[] dir_names
= last_path
.split("/");
588 for (String dir
: dir_names
)
591 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
592 while(!mStorageManager
.fileExists(generatePath(mParents
)) && mParents
.size() > 1){
599 public boolean onOptionsItemSelected(MenuItem item
) {
600 boolean retval
= true
;
601 switch (item
.getItemId()) {
602 case android
.R
.id
.home
: {
603 if((mParents
.size() > 1)) {
609 retval
= super.onOptionsItemSelected(item
);