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
.authentication
.PinCheck
;
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
.utils
.Log_OC
;
68 import com
.owncloud
.android
.utils
.DisplayUtils
;
71 * This can be used to upload things to an ownCloud instance.
73 * @author Bartek Przybylski
76 public class Uploader
extends SherlockListActivity
implements OnItemClickListener
, android
.view
.View
.OnClickListener
{
77 private static final String TAG
= "ownCloudUploader";
79 private Account mAccount
;
80 private AccountManager mAccountManager
;
81 private Stack
<String
> mParents
;
82 private ArrayList
<Parcelable
> mStreamsToUpload
;
83 private boolean mCreateDir
;
84 private String mUploadPath
;
85 private FileDataStorageManager mStorageManager
;
88 private final static int DIALOG_NO_ACCOUNT
= 0;
89 private final static int DIALOG_WAITING
= 1;
90 private final static int DIALOG_NO_STREAM
= 2;
91 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
93 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
96 protected void onCreate(Bundle savedInstanceState
) {
97 super.onCreate(savedInstanceState
);
98 mParents
= new Stack
<String
>();
101 if (PinCheck
.checkIfPinEntry()){
102 Intent i
= new Intent(MainApp
.getAppContext(), PinCodeActivity
.class);
103 i
.putExtra(PinCodeActivity
.EXTRA_ACTIVITY
, "ownCloudUploader");
107 ActionBar actionBar
= getSupportActionBar();
108 actionBar
.setIcon(DisplayUtils
.getSeasonalIconId());
110 if (prepareStreamsToUpload()) {
111 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
112 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAccountType());
113 if (accounts
.length
== 0) {
114 Log_OC
.i(TAG
, "No ownCloud account is available");
115 showDialog(DIALOG_NO_ACCOUNT
);
116 } else if (accounts
.length
> 1) {
117 Log_OC
.i(TAG
, "More then one ownCloud is available");
118 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
120 mAccount
= accounts
[0];
121 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
123 populateDirectoryList();
128 showDialog(DIALOG_NO_STREAM
);
133 protected Dialog
onCreateDialog(final int id
) {
134 final AlertDialog
.Builder builder
= new Builder(this);
137 ProgressDialog pDialog
= new ProgressDialog(this);
138 pDialog
.setIndeterminate(false
);
139 pDialog
.setCancelable(false
);
140 pDialog
.setMessage(getResources().getString(R
.string
.uploader_info_uploading
));
142 case DIALOG_NO_ACCOUNT
:
143 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
144 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
145 builder
.setMessage(String
.format(getString(R
.string
.uploader_wrn_no_account_text
), getString(R
.string
.app_name
)));
146 builder
.setCancelable(false
);
147 builder
.setPositiveButton(R
.string
.uploader_wrn_no_account_setup_btn_text
, new OnClickListener() {
149 public void onClick(DialogInterface dialog
, int which
) {
150 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
151 // using string value since in API7 this
152 // constatn is not defined
153 // in API7 < this constatant is defined in
154 // Settings.ADD_ACCOUNT_SETTINGS
155 // and Settings.EXTRA_AUTHORITIES
156 Intent intent
= new Intent(android
.provider
.Settings
.ACTION_ADD_ACCOUNT
);
157 intent
.putExtra("authorities", new String
[] { MainApp
.getAuthTokenType() });
158 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
160 // since in API7 there is no direct call for
161 // account setup, so we need to
162 // show our own AccountSetupAcricity, get
163 // desired results and setup
164 // everything for ourself
165 Intent intent
= new Intent(getBaseContext(), AccountAuthenticator
.class);
166 startActivityForResult(intent
, REQUEST_CODE_SETUP_ACCOUNT
);
170 builder
.setNegativeButton(R
.string
.uploader_wrn_no_account_quit_btn_text
, new OnClickListener() {
172 public void onClick(DialogInterface dialog
, int which
) {
176 return builder
.create();
177 case DIALOG_MULTIPLE_ACCOUNT
:
178 CharSequence ac
[] = new CharSequence
[mAccountManager
.getAccountsByType(MainApp
.getAccountType()).length
];
179 for (int i
= 0; i
< ac
.length
; ++i
) {
180 ac
[i
] = DisplayUtils
.convertIdn(mAccountManager
.getAccountsByType(MainApp
.getAccountType())[i
].name
, false
);
182 builder
.setTitle(R
.string
.common_choose_account
);
183 builder
.setItems(ac
, new OnClickListener() {
185 public void onClick(DialogInterface dialog
, int which
) {
186 mAccount
= mAccountManager
.getAccountsByType(MainApp
.getAccountType())[which
];
187 mStorageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
189 populateDirectoryList();
192 builder
.setCancelable(true
);
193 builder
.setOnCancelListener(new OnCancelListener() {
195 public void onCancel(DialogInterface dialog
) {
200 return builder
.create();
201 case DIALOG_NO_STREAM
:
202 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
203 builder
.setTitle(R
.string
.uploader_wrn_no_content_title
);
204 builder
.setMessage(R
.string
.uploader_wrn_no_content_text
);
205 builder
.setCancelable(false
);
206 builder
.setNegativeButton(R
.string
.common_cancel
, new OnClickListener() {
208 public void onClick(DialogInterface dialog
, int which
) {
212 return builder
.create();
214 throw new IllegalArgumentException("Unknown dialog id: " + id
);
218 class a
implements OnClickListener
{
222 public a(String path
, EditText dirname
) {
228 public void onClick(DialogInterface dialog
, int which
) {
229 Uploader
.this.mUploadPath
= mPath
+ mDirname
.getText().toString();
230 Uploader
.this.mCreateDir
= true
;
236 public void onBackPressed() {
238 if (mParents
.size() <= 1) {
239 super.onBackPressed();
243 populateDirectoryList();
248 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
, long id
) {
249 // click on folder in the list
250 Log_OC
.d(TAG
, "on item click");
251 Vector
<OCFile
> tmpfiles
= mStorageManager
.getFolderContent(mFile
);
252 if (tmpfiles
.size() <= 0) return;
254 Vector
<OCFile
> files
= new Vector
<OCFile
>();
255 for (OCFile f
: tmpfiles
)
258 if (files
.size() < position
) {
259 throw new IndexOutOfBoundsException("Incorrect item selected");
261 mParents
.push(files
.get(position
).getFileName());
262 populateDirectoryList();
266 public void onClick(View v
) {
269 case R
.id
.uploader_choose_folder
:
270 mUploadPath
= ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
271 for (String p
: mParents
)
272 mUploadPath
+= p
+ OCFile
.PATH_SEPARATOR
;
273 Log_OC
.d(TAG
, "Uploading file to dir " + mUploadPath
);
279 throw new IllegalArgumentException("Wrong element clicked");
284 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
285 super.onActivityResult(requestCode
, resultCode
, data
);
286 Log_OC
.i(TAG
, "result received. req: " + requestCode
+ " res: " + resultCode
);
287 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
288 dismissDialog(DIALOG_NO_ACCOUNT
);
289 if (resultCode
== RESULT_CANCELED
) {
292 Account
[] accounts
= mAccountManager
.getAccountsByType(MainApp
.getAuthTokenType());
293 if (accounts
.length
== 0) {
294 showDialog(DIALOG_NO_ACCOUNT
);
296 // there is no need for checking for is there more then one
297 // account at this point
298 // since account setup can set only one account at time
299 mAccount
= accounts
[0];
300 populateDirectoryList();
305 private void populateDirectoryList() {
306 setContentView(R
.layout
.uploader_layout
);
308 String current_dir
= mParents
.peek();
309 if(current_dir
.equals("")){
310 getSupportActionBar().setTitle(getString(R
.string
.default_display_name_for_root_folder
));
313 getSupportActionBar().setTitle(current_dir
);
315 boolean notRoot
= (mParents
.size() > 1);
316 ActionBar actionBar
= getSupportActionBar();
317 actionBar
.setDisplayHomeAsUpEnabled(notRoot
);
318 actionBar
.setHomeButtonEnabled(notRoot
);
320 String full_path
= generatePath(mParents
);
322 Log_OC
.d(TAG
, "Populating view with content of : " + full_path
);
324 mFile
= mStorageManager
.getFileByPath(full_path
);
326 Vector
<OCFile
> files
= mStorageManager
.getFolderContent(mFile
);
327 List
<HashMap
<String
, Object
>> data
= new LinkedList
<HashMap
<String
,Object
>>();
328 for (OCFile f
: files
) {
329 HashMap
<String
, Object
> h
= new HashMap
<String
, Object
>();
331 h
.put("dirname", f
.getFileName());
335 SimpleAdapter sa
= new SimpleAdapter(this,
337 R
.layout
.uploader_list_item_layout
,
338 new String
[] {"dirname"},
339 new int[] {R
.id
.textView1
});
341 Button btn
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
342 btn
.setOnClickListener(this);
343 getListView().setOnItemClickListener(this);
347 private String
generatePath(Stack
<String
> dirs
) {
348 String full_path
= "";
350 for (String a
: dirs
)
351 full_path
+= a
+ "/";
355 private boolean prepareStreamsToUpload() {
356 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
357 mStreamsToUpload
= new ArrayList
<Parcelable
>();
358 mStreamsToUpload
.add(getIntent().getParcelableExtra(Intent
.EXTRA_STREAM
));
359 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
360 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(Intent
.EXTRA_STREAM
);
362 return (mStreamsToUpload
!= null
&& mStreamsToUpload
.get(0) != null
);
365 public void uploadFiles() {
368 ArrayList
<String
> local
= new ArrayList
<String
>();
369 ArrayList
<String
> remote
= new ArrayList
<String
>();
371 // this checks the mimeType
372 for (Parcelable mStream
: mStreamsToUpload
) {
374 Uri uri
= (Uri
) mStream
;
376 if (uri
.getScheme().equals("content")) {
378 String mimeType
= getContentResolver().getType(uri
);
380 if (mimeType
.contains("image")) {
381 String
[] CONTENT_PROJECTION
= { Images
.Media
.DATA
, Images
.Media
.DISPLAY_NAME
, Images
.Media
.MIME_TYPE
, Images
.Media
.SIZE
};
382 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
384 int index
= c
.getColumnIndex(Images
.Media
.DATA
);
385 String data
= c
.getString(index
);
387 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Images
.Media
.DISPLAY_NAME
)));
390 else if (mimeType
.contains("video")) {
391 String
[] CONTENT_PROJECTION
= { Video
.Media
.DATA
, Video
.Media
.DISPLAY_NAME
, Video
.Media
.MIME_TYPE
, Video
.Media
.SIZE
, Video
.Media
.DATE_MODIFIED
};
392 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
394 int index
= c
.getColumnIndex(Video
.Media
.DATA
);
395 String data
= c
.getString(index
);
397 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Video
.Media
.DISPLAY_NAME
)));
400 else if (mimeType
.contains("audio")) {
401 String
[] CONTENT_PROJECTION
= { Audio
.Media
.DATA
, Audio
.Media
.DISPLAY_NAME
, Audio
.Media
.MIME_TYPE
, Audio
.Media
.SIZE
};
402 Cursor c
= getContentResolver().query(uri
, CONTENT_PROJECTION
, null
, null
, null
);
404 int index
= c
.getColumnIndex(Audio
.Media
.DATA
);
405 String data
= c
.getString(index
);
407 remote
.add(mUploadPath
+ c
.getString(c
.getColumnIndex(Audio
.Media
.DISPLAY_NAME
)));
411 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() + "://", "");
412 // cut everything whats before mnt. It occured to me that sometimes apps send their name into the URI
413 if (filePath
.contains("mnt")) {
414 String splitedFilePath
[] = filePath
.split("/mnt");
415 filePath
= splitedFilePath
[1];
417 final File file
= new File(filePath
);
418 local
.add(file
.getAbsolutePath());
419 remote
.add(mUploadPath
+ file
.getName());
422 } else if (uri
.getScheme().equals("file")) {
423 String filePath
= Uri
.decode(uri
.toString()).replace(uri
.getScheme() + "://", "");
424 if (filePath
.contains("mnt")) {
425 String splitedFilePath
[] = filePath
.split("/mnt");
426 filePath
= splitedFilePath
[1];
428 final File file
= new File(filePath
);
429 local
.add(file
.getAbsolutePath());
430 remote
.add(mUploadPath
+ file
.getName());
433 throw new SecurityException();
437 throw new SecurityException();
440 Intent intent
= new Intent(getApplicationContext(), FileUploader
.class);
441 intent
.putExtra(FileUploader
.KEY_UPLOAD_TYPE
, FileUploader
.UPLOAD_MULTIPLE_FILES
);
442 intent
.putExtra(FileUploader
.KEY_LOCAL_FILE
, local
.toArray(new String
[local
.size()]));
443 intent
.putExtra(FileUploader
.KEY_REMOTE_FILE
, remote
.toArray(new String
[remote
.size()]));
444 intent
.putExtra(FileUploader
.KEY_ACCOUNT
, mAccount
);
445 startService(intent
);
447 //Save the path to shared preferences
448 SharedPreferences
.Editor appPrefs
= PreferenceManager
449 .getDefaultSharedPreferences(getApplicationContext()).edit();
450 appPrefs
.putString("last_upload_path", mUploadPath
);
456 } catch (SecurityException e
) {
457 String message
= String
.format(getString(R
.string
.uploader_error_forbidden_content
), getString(R
.string
.app_name
));
458 Toast
.makeText(this, message
, Toast
.LENGTH_LONG
).show();
463 * Loads the target folder initialize shown to the user.
465 * The target account has to be chosen before this method is called.
467 private void initTargetFolder() {
468 if (mStorageManager
== null
) {
469 throw new IllegalStateException("Do not call this method before initializing mStorageManager");
472 SharedPreferences appPreferences
= PreferenceManager
473 .getDefaultSharedPreferences(getApplicationContext());
475 String last_path
= appPreferences
.getString("last_upload_path", "");
476 // "/" equals root-directory
477 if(last_path
.equals("/")) {
481 String
[] dir_names
= last_path
.split("/");
482 for (String dir
: dir_names
)
485 //Make sure that path still exists, if it doesn't pop the stack and try the previous path
486 while(!mStorageManager
.fileExists(generatePath(mParents
)) && mParents
.size() > 1){
493 public boolean onOptionsItemSelected(MenuItem item
) {
494 boolean retval
= true
;
495 switch (item
.getItemId()) {
496 case android
.R
.id
.home
: {
497 if((mParents
.size() > 1)) {
503 retval
= super.onOptionsItemSelected(item
);