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
.database
.Cursor
;
42 import android
.net
.Uri
;
43 import android
.os
.Bundle
;
44 import android
.os
.Parcelable
;
45 import android
.preference
.PreferenceManager
;
46 import android
.provider
.MediaStore
.Audio
;
47 import android
.provider
.MediaStore
.Images
;
48 import android
.provider
.MediaStore
.Video
;
49 import android
.view
.View
;
50 import android
.widget
.AdapterView
;
51 import android
.widget
.AdapterView
.OnItemClickListener
;
52 import android
.widget
.Button
;
53 import android
.widget
.EditText
;
54 import android
.widget
.SimpleAdapter
;
55 import android
.widget
.Toast
;
57 import com
.actionbarsherlock
.app
.ActionBar
;
58 import com
.actionbarsherlock
.app
.SherlockListActivity
;
59 import com
.actionbarsherlock
.view
.MenuItem
;
60 import com
.owncloud
.android
.MainApp
;
61 import com
.owncloud
.android
.R
;
62 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
63 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
64 import com
.owncloud
.android
.datamodel
.OCFile
;
65 import com
.owncloud
.android
.files
.services
.FileUploader
;
66 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
67 import com
.owncloud
.android
.utils
.DisplayUtils
;
70 * This can be used to upload things to an ownCloud instance.
72 * @author Bartek Przybylski
75 public class Uploader
extends SherlockListActivity
implements OnItemClickListener
, android
.view
.View
.OnClickListener
{
76 private static final String TAG
= "ownCloudUploader";
78 private Account mAccount
;
79 private AccountManager mAccountManager
;
80 private Stack
<String
> mParents
;
81 private ArrayList
<Parcelable
> mStreamsToUpload
;
82 private boolean mCreateDir
;
83 private String mUploadPath
;
84 private FileDataStorageManager mStorageManager
;
87 private final static int DIALOG_NO_ACCOUNT
= 0;
88 private final static int DIALOG_WAITING
= 1;
89 private final static int DIALOG_NO_STREAM
= 2;
90 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
92 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
95 protected void onCreate(Bundle savedInstanceState
) {
96 super.onCreate(savedInstanceState
);
97 mParents
= new Stack
<String
>();
99 ActionBar actionBar
= getSupportActionBar();
100 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
102 if (prepareStreamsToUpload()) {
103 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
104 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAccountType());
105 if (accounts
.length
== 0) {
106 Log_OC
.i(TAG
, "No ownCloud account is available");
107 showDialog(DIALOG_NO_ACCOUNT
);
108 } else if (accounts
.length
> 1) {
109 Log_OC
.i(TAG
, "More then one ownCloud is available");
110 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
112 mAccount
= accounts
[0];
113 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
115 populateDirectoryList();
120 showDialog(DIALOG_NO_STREAM
);
125 protected Dialog
onCreateDialog(final int id
) {
126 final AlertDialog
.Builder builder
= new Builder(this);
129 ProgressDialog pDialog
= new ProgressDialog(this);
130 pDialog
.setIndeterminate(false
);
131 pDialog
.setCancelable(false
);
132 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
134 case DIALOG_NO_ACCOUNT
:
135 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
136 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
137 builder
.setMessage(String
.format(getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
138 builder
.setCancelable(false
);
139 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
141 public void onClick(DialogInterface dialog
, int which
) {
142 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
143 // using string value since in API7 this
144 // constatn is not defined
145 // in API7 < this constatant is defined in
146 // Settings.ADD_ACCOUNT_SETTINGS
147 // and Settings.EXTRA_AUTHORITIES
148 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
149 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
150 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
152 // since in API7 there is no direct call for
153 // account setup, so we need to
154 // show our own AccountSetupAcricity, get
155 // desired results and setup
156 // everything for ourself
157 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
158 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
162 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
164 public void onClick(DialogInterface dialog
, int which
) {
168 return builder
.create();
169 case DIALOG_MULTIPLE_ACCOUNT
:
170 CharSequence ac
[] = new CharSequence
[mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
171 for (int i
= 0; i
< ac
.length
; ++i
) {
172 ac
[i
] = DisplayUtils
.convertIdn(mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
174 builder
.setTitle(R
.string
.common_choose_account
);
175 builder
.setItems(ac
, new OnClickListener() {
177 public void onClick(DialogInterface dialog
, int which
) {
178 mAccount
= mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
];
179 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
181 populateDirectoryList();
184 builder
.setCancelable(true
);
185 builder
.setOnCancelListener(new OnCancelListener() {
187 public void onCancel(DialogInterface dialog
) {
192 return builder
.create();
193 case DIALOG_NO_STREAM
:
194 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
195 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
196 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
197 builder
.setCancelable(false
);
198 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
200 public void onClick(DialogInterface dialog
, int which
) {
204 return builder
.create();
206 throw new IllegalArgumentException("Unknown dialog id: " + id
);
210 class a
implements OnClickListener
{
214 public a(String path
, EditText dirname
) {
220 public void onClick(DialogInterface dialog
, int which
) {
221 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
222 Uploader
.this.mCreateDir
= true
;
228 public void onBackPressed() {
230 if (mParents
.size() <= 1) {
231 super.onBackPressed();
235 populateDirectoryList();
240 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
241 // click on folder in the list
242 Log_OC
.d(TAG
, "on item click");
243 Vector
<OCFile
> tmpfiles
= mStorageManager
.getFolderContent(mFile
, false
);
244 if (tmpfiles
.size() <= 0) return;
246 Vector
<OCFile
> files
= new Vector
<OCFile
>();
247 for (OCFile f
: tmpfiles
)
250 if (files
.size() < position
) {
251 throw new IndexOutOfBoundsException("Incorrect item selected");
253 mParents
.push(files
.get(position
).getFileName());
254 populateDirectoryList();
258 public void onClick(View v
) {
261 case R
.id
.uploader_choose_folder
:
262 mUploadPath
= ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
263 for (String p
: mParents
)
264 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
265 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
271 throw new IllegalArgumentException("Wrong element clicked");
276 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
277 super.onActivityResult(requestCode
, resultCode
, data
);
278 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
279 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
280 dismissDialog(DIALOG_NO_ACCOUNT
);
281 if (resultCode
== RESULT_CANCELED
) {
284 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
285 if (accounts
.length
== 0) {
286 showDialog(DIALOG_NO_ACCOUNT
);
288 // there is no need for checking for is there more then one
289 // account at this point
290 // since account setup can set only one account at time
291 mAccount
= accounts
[0];
292 populateDirectoryList();
297 private void populateDirectoryList() {
298 setContentView(R
.layout
.uploader_layout
);
300 String current_dir
= mParents
.peek();
301 if(current_dir
.equals("")){
302 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
305 getSupportActionBar().setTitle(current_dir
);
307 boolean notRoot
= (mParents
.size() > 1);
308 ActionBar actionBar
= getSupportActionBar();
309 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
310 actionBar
.setHomeButtonEnabled(notRoot
);
312 String full_path
= generatePath(mParents
);
314 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
316 mFile
= mStorageManager
.getFileByPath(full_path
);
318 Vector
<OCFile
> files
= mStorageManager
.getFolderContent(mFile
, false
);
319 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
320 for (OCFile f
: files
) {
321 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
323 h
.put("dirname", f
.getFileName());
327 SimpleAdapter sa
= new SimpleAdapter(this,
329 R
.layout
.uploader_list_item_layout
,
330 new String
[] {"dirname"},
331 new int[] {R
.id
.drawer_username
});
333 Button btn
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
334 btn
.setOnClickListener(this);
335 getListView().setOnItemClickListener(this);
339 private String
generatePath(Stack
<String
> dirs
) {
340 String full_path
= "";
342 for (String a
: dirs
)
343 full_path
+= a
+ "/";
347 private boolean prepareStreamsToUpload() {
348 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
349 mStreamsToUpload
= new ArrayList
<Parcelable
>();
350 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
351 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
352 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
354 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
357 public void uploadFiles() {
360 ArrayList
<String
> local
= new ArrayList
<String
>();
361 ArrayList
<String
> remote
= new ArrayList
<String
>();
363 // this checks the mimeType
364 for (Parcelable mStream
: mStreamsToUpload
) {
366 Uri uri
= (Uri
) mStream
;
368 if (uri
.getScheme().equals("content")) {
370 String mimeType
= getContentResolver().getType(uri
);
372 if (mimeType
.contains("image")) {
373 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
, Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
, Images
.Media
.SIZE
};
374 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
376 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
377 String data
= c
.getString(index
);
379 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
382 else if (mimeType
.contains("video")) {
383 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
, Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
, Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
384 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
386 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
387 String data
= c
.getString(index
);
389 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
392 else if (mimeType
.contains("audio")) {
393 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
, Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
, Audio
.Media
.SIZE
};
394 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
396 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
397 String data
= c
.getString(index
);
399 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
403 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() + "://", "");
404 // cut everything whats before mnt. It occured to me that sometimes apps send their name into the URI
405 if (filePath
.contains("mnt")) {
406 String splitedFilePath
[] = filePath
.split("/mnt");
407 filePath
= splitedFilePath
[1];
409 final File file
= new File(filePath
);
410 local
.add(file
.getAbsolutePath());
411 remote
.add(mUploadPath
+ file
.getName());
414 } else if (uri
.getScheme().equals("file")) {
415 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() + "://", "");
416 if (filePath
.contains("mnt")) {
417 String splitedFilePath
[] = filePath
.split("/mnt");
418 filePath
= splitedFilePath
[1];
420 final File file
= new File(filePath
);
421 local
.add(file
.getAbsolutePath());
422 remote
.add(mUploadPath
+ file
.getName());
425 throw new SecurityException();
429 throw new SecurityException();
432 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
433 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
434 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
435 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remote
.toArray(new String
[remote
.size()]));
436 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, mAccount
);
437 startService(intent
);
439 //Save the path to shared preferences
440 SharedPreferences
.Editor appPrefs
= PreferenceManager
441 .getDefaultSharedPreferences(getApplicationContext()).edit();
442 appPrefs
.putString("last_upload_path", mUploadPath
);
448 } catch (SecurityException e
) {
449 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
), getString(R
.string
.app_name
));
450 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
455 * Loads the target folder initialize shown to the user.
457 * The target account has to be chosen before this method is called.
459 private void initTargetFolder() {
460 if (mStorageManager
== null
) {
461 throw new IllegalStateException("Do not call this method before initializing mStorageManager");
464 SharedPreferences appPreferences
= PreferenceManager
465 .getDefaultSharedPreferences(getApplicationContext());
467 String last_path
= appPreferences
.getString("last_upload_path", "");
468 // "/" equals root-directory
469 if(last_path
.equals("/")) {
473 String
[] dir_names
= last_path
.split("/");
474 for (String dir
: dir_names
)
477 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
478 while(!mStorageManager
.fileExists(generatePath(mParents
)) && mParents
.size() > 1){
485 public boolean onOptionsItemSelected(MenuItem item
) {
486 boolean retval
= true
;
487 switch (item
.getItemId()) {
488 case android
.R
.id
.home
: {
489 if((mParents
.size() > 1)) {
495 retval
= super.onOptionsItemSelected(item
);