1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.activity
;
22 import java
.util
.ArrayList
;
23 import java
.util
.HashMap
;
24 import java
.util
.LinkedList
;
25 import java
.util
.List
;
26 import java
.util
.Stack
;
27 import java
.util
.Vector
;
29 import android
.accounts
.Account
;
30 import android
.accounts
.AccountManager
;
31 import android
.app
.AlertDialog
;
32 import android
.app
.AlertDialog
.Builder
;
33 import android
.app
.Dialog
;
34 import android
.app
.ProgressDialog
;
35 import android
.content
.Context
;
36 import android
.content
.DialogInterface
;
37 import android
.content
.DialogInterface
.OnCancelListener
;
38 import android
.content
.DialogInterface
.OnClickListener
;
39 import android
.content
.Intent
;
40 import android
.content
.SharedPreferences
;
41 import android
.content
.res
.Resources
.NotFoundException
;
42 import android
.database
.Cursor
;
43 import android
.net
.Uri
;
44 import android
.os
.Bundle
;
45 import android
.os
.Parcelable
;
46 import android
.preference
.PreferenceManager
;
47 import android
.provider
.MediaStore
.Audio
;
48 import android
.provider
.MediaStore
.Images
;
49 import android
.provider
.MediaStore
.Video
;
50 import android
.view
.View
;
51 import android
.widget
.AdapterView
;
52 import android
.widget
.AdapterView
.OnItemClickListener
;
53 import android
.widget
.Button
;
54 import android
.widget
.EditText
;
55 import android
.widget
.ListView
;
56 import android
.widget
.SimpleAdapter
;
57 import android
.widget
.Toast
;
59 import com
.actionbarsherlock
.app
.ActionBar
;
60 import com
.actionbarsherlock
.view
.MenuItem
;
61 import com
.owncloud
.android
.MainApp
;
62 import com
.owncloud
.android
.R
;
63 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
64 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
65 import com
.owncloud
.android
.datamodel
.OCFile
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
;
67 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
68 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
69 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
70 import com
.owncloud
.android
.operations
.CreateFolderOperation
;
71 import com
.owncloud
.android
.ui
.dialog
.CreateFolderDialogFragment
;
72 import com
.owncloud
.android
.utils
.DisplayUtils
;
73 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
77 * This can be used to upload things to an ownCloud instance.
79 * @author Bartek Przybylski
82 public class Uploader
extends FileActivity
implements OnItemClickListener
, android
.view
.View
.OnClickListener
{
83 private static final String TAG
= "ownCloudUploader";
85 private Account mAccount
;
86 private AccountManager mAccountManager
;
87 private Stack
<String
> mParents
;
88 private ArrayList
<Parcelable
> mStreamsToUpload
;
89 private boolean mCreateDir
;
90 private String mUploadPath
;
91 private FileDataStorageManager mStorageManager
;
94 private final static int DIALOG_NO_ACCOUNT
= 0;
95 private final static int DIALOG_WAITING
= 1;
96 private final static int DIALOG_NO_STREAM
= 2;
97 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
99 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
102 protected void onCreate(Bundle savedInstanceState
) {
103 super.onCreate(savedInstanceState
);
104 mParents
= new Stack
<String
>();
106 ActionBar actionBar
= getSupportActionBar();
107 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
109 if (prepareStreamsToUpload()) {
110 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
111 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAccountType());
112 if (accounts
.length
== 0) {
113 Log_OC
.i(TAG
, "No ownCloud account is available");
114 showDialog(DIALOG_NO_ACCOUNT
);
115 } else if (accounts
.length
> 1) {
116 Log_OC
.i(TAG
, "More then one ownCloud is available");
117 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
119 mAccount
= accounts
[0];
120 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
122 populateDirectoryList();
127 showDialog(DIALOG_NO_STREAM
);
132 protected Dialog
onCreateDialog(final int id
) {
133 final AlertDialog
.Builder builder
= new Builder(this);
136 ProgressDialog pDialog
= new ProgressDialog(this);
137 pDialog
.setIndeterminate(false
);
138 pDialog
.setCancelable(false
);
139 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
141 case DIALOG_NO_ACCOUNT
:
142 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
143 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
144 builder
.setMessage(String
.format(getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
145 builder
.setCancelable(false
);
146 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
148 public void onClick(DialogInterface dialog
, int which
) {
149 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
150 // using string value since in API7 this
151 // constatn is not defined
152 // in API7 < this constatant is defined in
153 // Settings.ADD_ACCOUNT_SETTINGS
154 // and Settings.EXTRA_AUTHORITIES
155 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
156 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
157 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
159 // since in API7 there is no direct call for
160 // account setup, so we need to
161 // show our own AccountSetupAcricity, get
162 // desired results and setup
163 // everything for ourself
164 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
165 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
169 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
171 public void onClick(DialogInterface dialog
, int which
) {
175 return builder
.create();
176 case DIALOG_MULTIPLE_ACCOUNT
:
177 CharSequence ac
[] = new CharSequence
[mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
178 for (int i
= 0; i
< ac
.length
; ++i
) {
179 ac
[i
] = DisplayUtils
.convertIdn(mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
181 builder
.setTitle(R
.string
.common_choose_account
);
182 builder
.setItems(ac
, new OnClickListener() {
184 public void onClick(DialogInterface dialog
, int which
) {
185 mAccount
= mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
];
186 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
188 populateDirectoryList();
191 builder
.setCancelable(true
);
192 builder
.setOnCancelListener(new OnCancelListener() {
194 public void onCancel(DialogInterface dialog
) {
199 return builder
.create();
200 case DIALOG_NO_STREAM
:
201 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
202 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
203 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
204 builder
.setCancelable(false
);
205 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
207 public void onClick(DialogInterface dialog
, int which
) {
211 return builder
.create();
213 throw new IllegalArgumentException("Unknown dialog id: " + id
);
217 class a
implements OnClickListener
{
221 public a(String path
, EditText dirname
) {
227 public void onClick(DialogInterface dialog
, int which
) {
228 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
229 Uploader
.this.mCreateDir
= true
;
235 public void onBackPressed() {
237 if (mParents
.size() <= 1) {
238 super.onBackPressed();
242 populateDirectoryList();
247 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
248 // click on folder in the list
249 Log_OC
.d(TAG
, "on item click");
250 Vector
<OCFile
> tmpfiles
= mStorageManager
.getFolderContent(mFile
);
251 if (tmpfiles
.size() <= 0) return;
253 Vector
<OCFile
> files
= new Vector
<OCFile
>();
254 for (OCFile f
: tmpfiles
)
257 if (files
.size() < position
) {
258 throw new IndexOutOfBoundsException("Incorrect item selected");
260 mParents
.push(files
.get(position
).getFileName());
261 populateDirectoryList();
265 public void onClick(View v
) {
268 case R
.id
.uploader_choose_folder
:
269 mUploadPath
= ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
270 for (String p
: mParents
)
271 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
272 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
278 case R
.id
.uploader_new_folder
:
279 CreateFolderDialogFragment dialog
= CreateFolderDialogFragment
.newInstance(mFile
);
280 dialog
.show(getSupportFragmentManager(), "createdirdialog");
285 throw new IllegalArgumentException("Wrong element clicked");
290 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
291 super.onActivityResult(requestCode
, resultCode
, data
);
292 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
293 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
294 dismissDialog(DIALOG_NO_ACCOUNT
);
295 if (resultCode
== RESULT_CANCELED
) {
298 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
299 if (accounts
.length
== 0) {
300 showDialog(DIALOG_NO_ACCOUNT
);
302 // there is no need for checking for is there more then one
303 // account at this point
304 // since account setup can set only one account at time
305 mAccount
= accounts
[0];
306 populateDirectoryList();
311 private void populateDirectoryList() {
312 setContentView(R
.layout
.uploader_layout
);
314 ListView mListView
= (ListView
) findViewById(android
.R
.id
.list
);
316 String current_dir
= mParents
.peek();
317 if(current_dir
.equals("")){
318 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
321 getSupportActionBar().setTitle(current_dir
);
323 boolean notRoot
= (mParents
.size() > 1);
324 ActionBar actionBar
= getSupportActionBar();
325 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
326 actionBar
.setHomeButtonEnabled(notRoot
);
328 String full_path
= generatePath(mParents
);
330 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
332 mFile
= mStorageManager
.getFileByPath(full_path
);
334 Vector
<OCFile
> files
= mStorageManager
.getFolderContent(mFile
);
335 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
336 for (OCFile f
: files
) {
337 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
339 h
.put("dirname", f
.getFileName());
343 SimpleAdapter sa
= new SimpleAdapter(this,
345 R
.layout
.uploader_list_item_layout
,
346 new String
[] {"dirname"},
347 new int[] {R
.id
.textView1
});
349 mListView
.setAdapter(sa
);
350 Button btnChooseFolder
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
351 btnChooseFolder
.setOnClickListener(this);
353 Button btnNewFolder
= (Button
) findViewById(R
.id
.uploader_new_folder
);
354 btnNewFolder
.setOnClickListener(this);
356 mListView
.setOnItemClickListener(this);
360 private String
generatePath(Stack
<String
> dirs
) {
361 String full_path
= "";
363 for (String a
: dirs
)
364 full_path
+= a
+ "/";
368 private boolean prepareStreamsToUpload() {
369 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
370 mStreamsToUpload
= new ArrayList
<Parcelable
>();
371 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
372 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
373 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
375 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
378 public void uploadFiles() {
381 ArrayList
<String
> local
= new ArrayList
<String
>();
382 ArrayList
<String
> remote
= new ArrayList
<String
>();
384 // this checks the mimeType
385 for (Parcelable mStream
: mStreamsToUpload
) {
387 Uri uri
= (Uri
) mStream
;
389 if (uri
.getScheme().equals("content")) {
391 String mimeType
= getContentResolver().getType(uri
);
393 if (mimeType
.contains("image")) {
394 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
, Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
, Images
.Media
.SIZE
};
395 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
397 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
398 String data
= c
.getString(index
);
400 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
403 else if (mimeType
.contains("video")) {
404 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
, Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
, Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
405 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
407 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
408 String data
= c
.getString(index
);
410 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
413 else if (mimeType
.contains("audio")) {
414 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
, Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
, Audio
.Media
.SIZE
};
415 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
417 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
418 String data
= c
.getString(index
);
420 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
424 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() + "://", "");
425 // cut everything whats before mnt. It occured to me that sometimes apps send their name into the URI
426 if (filePath
.contains("mnt")) {
427 String splitedFilePath
[] = filePath
.split("/mnt");
428 filePath
= splitedFilePath
[1];
430 final File file
= new File(filePath
);
431 local
.add(file
.getAbsolutePath());
432 remote
.add(mUploadPath
+ file
.getName());
435 } else if (uri
.getScheme().equals("file")) {
436 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() + "://", "");
437 if (filePath
.contains("mnt")) {
438 String splitedFilePath
[] = filePath
.split("/mnt");
439 filePath
= splitedFilePath
[1];
441 final File file
= new File(filePath
);
442 local
.add(file
.getAbsolutePath());
443 remote
.add(mUploadPath
+ file
.getName());
446 throw new SecurityException();
450 throw new SecurityException();
453 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
454 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
455 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
456 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remote
.toArray(new String
[remote
.size()]));
457 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, mAccount
);
458 startService(intent
);
460 //Save the path to shared preferences
461 SharedPreferences
.Editor appPrefs
= PreferenceManager
462 .getDefaultSharedPreferences(getApplicationContext()).edit();
463 appPrefs
.putString("last_upload_path", mUploadPath
);
469 } catch (SecurityException e
) {
470 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
), getString(R
.string
.app_name
));
471 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
476 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
477 super.onRemoteOperationFinish(operation
, result
);
480 if (operation
instanceof CreateFolderOperation
) {
481 onCreateFolderOperationFinish((CreateFolderOperation
)operation
, result
);
487 * Updates the view associated to the activity after the finish of an operation trying create a new folder
489 * @param operation Creation operation performed.
490 * @param result Result of the creation.
492 private void onCreateFolderOperationFinish(CreateFolderOperation operation
, RemoteOperationResult result
) {
493 if (result
.isSuccess()) {
494 dismissLoadingDialog();
495 populateDirectoryList();
497 dismissLoadingDialog();
499 Toast msg
= Toast
.makeText(this,
500 ErrorMessageAdapter
.getErrorCauseMessage(result
, operation
, getResources()),
504 } catch (NotFoundException e
) {
505 Log_OC
.e(TAG
, "Error while trying to show fail message " , e
);
512 * Loads the target folder initialize shown to the user.
514 * The target account has to be chosen before this method is called.
516 private void initTargetFolder() {
517 if (mStorageManager
== null
) {
518 throw new IllegalStateException("Do not call this method before initializing mStorageManager");
521 SharedPreferences appPreferences
= PreferenceManager
522 .getDefaultSharedPreferences(getApplicationContext());
524 String last_path
= appPreferences
.getString("last_upload_path", "");
525 // "/" equals root-directory
526 if(last_path
.equals("/")) {
530 String
[] dir_names
= last_path
.split("/");
531 for (String dir
: dir_names
)
534 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
535 while(!mStorageManager
.fileExists(generatePath(mParents
)) && mParents
.size() > 1){
542 public boolean onOptionsItemSelected(MenuItem item
) {
543 boolean retval
= true
;
544 switch (item
.getItemId()) {
545 case android
.R
.id
.home
: {
546 if((mParents
.size() > 1)) {
552 retval
= super.onOptionsItemSelected(item
);