1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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/>.
18 package eu
.alefzero
.owncloud
;
21 import java
.net
.FileNameMap
;
22 import java
.net
.URLConnection
;
23 import java
.util
.ArrayList
;
24 import java
.util
.Stack
;
26 import android
.accounts
.Account
;
27 import android
.accounts
.AccountManager
;
28 import android
.app
.AlertDialog
;
29 import android
.app
.Dialog
;
30 import android
.app
.ListActivity
;
31 import android
.app
.ProgressDialog
;
32 import android
.app
.AlertDialog
.Builder
;
33 import android
.content
.ContentValues
;
34 import android
.content
.Context
;
35 import android
.content
.DialogInterface
;
36 import android
.content
.Intent
;
37 import android
.content
.DialogInterface
.OnCancelListener
;
38 import android
.content
.DialogInterface
.OnClickListener
;
39 import android
.database
.Cursor
;
40 import android
.net
.Uri
;
41 import android
.os
.Bundle
;
42 import android
.os
.Handler
;
43 import android
.os
.Parcelable
;
44 import android
.provider
.MediaStore
.Images
.Media
;
45 import android
.util
.Log
;
46 import android
.view
.View
;
47 import android
.view
.Window
;
48 import android
.view
.ViewGroup
.LayoutParams
;
49 import android
.widget
.AdapterView
;
50 import android
.widget
.Button
;
51 import android
.widget
.EditText
;
52 import android
.widget
.LinearLayout
;
53 import android
.widget
.ListView
;
54 import android
.widget
.SimpleCursorAdapter
;
55 import android
.widget
.Toast
;
56 import android
.widget
.AdapterView
.OnItemClickListener
;
57 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
58 import eu
.alefzero
.owncloud
.db
.ProviderMeta
;
59 import eu
.alefzero
.owncloud
.db
.ProviderMeta
.ProviderTableMeta
;
60 import eu
.alefzero
.webdav
.WebdavClient
;
61 import eu
.alefzero
.webdav
.WebdavUtils
;
64 * This can be used to upload things to an ownCloud instance.
66 * @author Bartek Przybylski
69 public class Uploader
extends ListActivity
implements OnItemClickListener
,
70 android
.view
.View
.OnClickListener
{
71 private static final String TAG
= "ownCloudUploader";
73 private Account mAccount
;
74 private AccountManager mAccountManager
;
75 private String mUsername
, mPassword
;
76 private Cursor mCursor
;
77 private Stack
<String
> mParents
;
78 private Thread mUploadThread
;
79 private Handler mHandler
;
80 private ArrayList
<Parcelable
> mStreamsToUpload
;
82 private final static int DIALOG_NO_ACCOUNT
= 0;
83 private final static int DIALOG_WAITING
= 1;
84 private final static int DIALOG_NO_STREAM
= 2;
85 private final static int DIALOG_MULTIPLE_ACCOUNT
= 3;
86 private final static int DIALOG_GET_DIRNAME
= 4;
88 private final static int REQUEST_CODE_SETUP_ACCOUNT
= 0;
91 protected void onCreate(Bundle savedInstanceState
) {
92 super.onCreate(savedInstanceState
);
93 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
94 mParents
= new Stack
<String
>();
95 mHandler
= new Handler();
96 if (getIntent().hasExtra(Intent
.EXTRA_STREAM
)) {
97 prepareStreamsToUpload();
98 mAccountManager
= (AccountManager
) getSystemService(Context
.ACCOUNT_SERVICE
);
99 Account
[] accounts
= mAccountManager
100 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
);
101 if (accounts
.length
== 0) {
102 Log
.i(TAG
, "No ownCloud account is available");
103 showDialog(DIALOG_NO_ACCOUNT
);
104 } else if (accounts
.length
> 1) {
105 Log
.i(TAG
, "More then one ownCloud is available");
106 showDialog(DIALOG_MULTIPLE_ACCOUNT
);
108 mAccount
= accounts
[0];
109 setContentView(R
.layout
.uploader_layout
);
110 populateDirectoryList();
113 showDialog(DIALOG_NO_STREAM
);
118 protected Dialog
onCreateDialog(final int id
) {
119 final AlertDialog
.Builder builder
= new Builder(this);
122 ProgressDialog pDialog
= new ProgressDialog(this);
123 pDialog
.setIndeterminate(false
);
124 pDialog
.setCancelable(false
);
125 pDialog
.setMessage(getResources().getString(
126 R
.string
.uploader_info_uploading
));
128 case DIALOG_NO_ACCOUNT
:
129 builder
.setIcon(android
.R
.drawable
.ic_dialog_alert
);
130 builder
.setTitle(R
.string
.uploader_wrn_no_account_title
);
131 builder
.setMessage(R
.string
.uploader_wrn_no_account_text
);
132 builder
.setCancelable(false
);
133 builder
.setPositiveButton(
134 R
.string
.uploader_wrn_no_account_setup_btn_text
,
135 new OnClickListener() {
136 public void onClick(DialogInterface dialog
, int which
) {
137 if (android
.os
.Build
.VERSION
.SDK_INT
> android
.os
.Build
.VERSION_CODES
.ECLAIR_MR1
) {
138 // using string value since in API7 this
139 // constatn is not defined
140 // in API7 < this constatant is defined in
141 // Settings.ADD_ACCOUNT_SETTINGS
142 // and Settings.EXTRA_AUTHORITIES
143 Intent intent
= new Intent(
144 "android.settings.ADD_ACCOUNT_SETTINGS");
147 new String
[] { AccountAuthenticator
.AUTH_TOKEN_TYPE
});
148 startActivityForResult(intent
,
149 REQUEST_CODE_SETUP_ACCOUNT
);
151 // since in API7 there is no direct call for
152 // account setup, so we need to
153 // show our own AccountSetupAcricity, get
154 // desired results and setup
155 // everything for ourself
156 Intent intent
= new Intent(getBaseContext(),
157 AccountAuthenticator
.class);
158 startActivityForResult(intent
,
159 REQUEST_CODE_SETUP_ACCOUNT
);
163 builder
.setNegativeButton(
164 R
.string
.uploader_wrn_no_account_quit_btn_text
,
165 new OnClickListener() {
166 public void onClick(DialogInterface dialog
, int which
) {
170 return builder
.create();
171 case DIALOG_GET_DIRNAME
:
172 final EditText dirName
= new EditText(getBaseContext());
173 builder
.setView(dirName
);
174 builder
.setTitle(R
.string
.uploader_info_dirname
);
176 if (mParents
.empty()) {
179 mCursor
= managedQuery(Uri
.withAppendedPath(
180 ProviderTableMeta
.CONTENT_URI_FILE
, mParents
.peek()),
181 null
, null
, null
, null
);
182 mCursor
.moveToFirst();
183 pathToUpload
= mCursor
.getString(mCursor
184 .getColumnIndex(ProviderTableMeta
.FILE_PATH
))
187 mCursor
.getColumnIndex(ProviderTableMeta
.FILE_NAME
))
188 .replace(" ", "%20");
190 a a
= new a(pathToUpload
, dirName
);
191 builder
.setPositiveButton(R
.string
.common_ok
, a
);
192 builder
.setNegativeButton(R
.string
.common_cancel
,
193 new OnClickListener() {
194 public void onClick(DialogInterface dialog
, int which
) {
198 return builder
.create();
199 case DIALOG_MULTIPLE_ACCOUNT
:
200 CharSequence ac
[] = new CharSequence
[mAccountManager
201 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
).length
];
202 for (int i
= 0; i
< ac
.length
; ++i
) {
203 ac
[i
] = mAccountManager
204 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
)[i
].name
;
206 builder
.setTitle(R
.string
.common_choose_account
);
207 builder
.setItems(ac
, new OnClickListener() {
208 public void onClick(DialogInterface dialog
, int which
) {
209 mAccount
= mAccountManager
210 .getAccountsByType(AccountAuthenticator
.ACCOUNT_TYPE
)[which
];
211 populateDirectoryList();
214 builder
.setCancelable(true
);
215 builder
.setOnCancelListener(new OnCancelListener() {
216 public void onCancel(DialogInterface dialog
) {
221 return builder
.create();
223 throw new IllegalArgumentException("Unknown dialog id: " + id
);
227 class a
implements OnClickListener
{
231 public a(String path
, EditText dirname
) {
236 public void onClick(DialogInterface dialog
, int which
) {
237 showDialog(DIALOG_WAITING
);
238 mUploadThread
= new Thread(new BackgroundUploader(mPath
239 + mDirname
.getText().toString(), mStreamsToUpload
,
241 mUploadThread
.start();
246 public void onBackPressed() {
248 if (mParents
.size() == 0) {
249 super.onBackPressed();
251 } else if (mParents
.size() == 1) {
253 mCursor
= managedQuery(ProviderTableMeta
.CONTENT_URI
, null
,
254 ProviderTableMeta
.FILE_CONTENT_TYPE
+ "=?",
255 new String
[] { "DIR" }, null
);
258 mCursor
= managedQuery(Uri
.withAppendedPath(
259 ProviderTableMeta
.CONTENT_URI_DIR
, mParents
.peek()), null
,
260 ProviderTableMeta
.FILE_CONTENT_TYPE
+ "=?",
261 new String
[] { "DIR" }, null
);
264 SimpleCursorAdapter sca
= new SimpleCursorAdapter(this,
265 R
.layout
.uploader_list_item_layout
, mCursor
,
266 new String
[] { ProviderTableMeta
.FILE_NAME
},
267 new int[] { R
.id
.textView1
});
271 public void onItemClick(AdapterView
<?
> parent
, View view
, int position
,
273 if (!mCursor
.moveToPosition(position
)) {
274 throw new IndexOutOfBoundsException("Incorrect item selected");
276 String _id
= mCursor
.getString(mCursor
277 .getColumnIndex(ProviderTableMeta
._ID
));
281 mCursor
= managedQuery(
282 Uri
.withAppendedPath(ProviderTableMeta
.CONTENT_URI_DIR
, _id
),
283 null
, ProviderTableMeta
.FILE_CONTENT_TYPE
+ "=?",
284 new String
[] { "DIR" }, null
);
285 SimpleCursorAdapter sca
= new SimpleCursorAdapter(this,
286 R
.layout
.uploader_list_item_layout
, mCursor
,
287 new String
[] { ProviderTableMeta
.FILE_NAME
},
288 new int[] { R
.id
.textView1
});
290 getListView().invalidate();
293 public void onClick(View v
) {
295 case R
.id
.uploader_choose_folder
:
296 String pathToUpload
= null
;
297 if (mParents
.empty()) {
300 mCursor
= managedQuery(Uri
.withAppendedPath(
301 ProviderTableMeta
.CONTENT_URI_FILE
, mParents
.peek()),
302 null
, null
, null
, null
);
303 mCursor
.moveToFirst();
304 pathToUpload
= mCursor
.getString(
305 mCursor
.getColumnIndex(ProviderTableMeta
.FILE_PATH
))
306 .replace(" ", "%20");
308 Log
.d(TAG
, "Uploading file to dir " + pathToUpload
);
310 showDialog(DIALOG_WAITING
);
311 mUploadThread
= new Thread(new BackgroundUploader(pathToUpload
,
312 mStreamsToUpload
, mHandler
));
313 mUploadThread
.start();
316 case android
.R
.id
.button1
: // dynamic action for create aditional dir
317 showDialog(DIALOG_GET_DIRNAME
);
320 throw new IllegalArgumentException("Wrong element clicked");
324 public void onUploadComplete(boolean uploadSucc
, String message
) {
325 dismissDialog(DIALOG_WAITING
);
326 Log
.i(TAG
, "UploadSucc: " + uploadSucc
+ " message: " + message
);
329 getResources().getString(R
.string
.uploader_upload_succeed
),
330 Toast
.LENGTH_SHORT
).show();
334 getResources().getString(R
.string
.uploader_upload_failed
)
335 + message
, Toast
.LENGTH_LONG
).show();
341 protected void onActivityResult(int requestCode
, int resultCode
, Intent data
) {
342 super.onActivityResult(requestCode
, resultCode
, data
);
343 Log
.i(TAG
, "result received. req: " + requestCode
+ " res: "
345 if (requestCode
== REQUEST_CODE_SETUP_ACCOUNT
) {
346 dismissDialog(DIALOG_NO_ACCOUNT
);
347 if (resultCode
== RESULT_CANCELED
) {
350 Account
[] accounts
= mAccountManager
351 .getAccountsByType(AccountAuthenticator
.AUTH_TOKEN_TYPE
);
352 if (accounts
.length
== 0) {
353 showDialog(DIALOG_NO_ACCOUNT
);
355 // there is no need for checking for is there more then one
356 // account at this point
357 // since account setup can set only one account at time
358 mAccount
= accounts
[0];
359 populateDirectoryList();
364 private void populateDirectoryList() {
365 mUsername
= mAccount
.name
.substring(0, mAccount
.name
.indexOf('@'));
366 mPassword
= mAccountManager
.getPassword(mAccount
);
367 setContentView(R
.layout
.uploader_layout
);
369 mCursor
= managedQuery(ProviderMeta
.ProviderTableMeta
.CONTENT_URI
,
370 null
, ProviderTableMeta
.FILE_NAME
+ "=? AND "
371 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
372 new String
[] { "/", mAccount
.name
}, null
);
374 if (mCursor
.moveToFirst()) {
375 mCursor
= managedQuery(
376 ProviderMeta
.ProviderTableMeta
.CONTENT_URI
,
378 ProviderTableMeta
.FILE_CONTENT_TYPE
+ "=? AND "
379 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=? AND "
380 + ProviderTableMeta
.FILE_PARENT
+ "=?",
384 mCursor
.getString(mCursor
385 .getColumnIndex(ProviderTableMeta
._ID
)) },
388 ListView lv
= getListView();
389 lv
.setOnItemClickListener(this);
390 SimpleCursorAdapter sca
= new SimpleCursorAdapter(this,
391 R
.layout
.uploader_list_item_layout
, mCursor
,
392 new String
[] { ProviderTableMeta
.FILE_NAME
},
393 new int[] { R
.id
.textView1
});
395 Button btn
= (Button
) findViewById(R
.id
.uploader_choose_folder
);
396 btn
.setOnClickListener(this);
397 // insert create new directory for multiple items uploading
398 if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
399 Button createDirBtn
= new Button(this);
400 createDirBtn
.setId(android
.R
.id
.button1
);
401 createDirBtn
.setText(R
.string
.uploader_btn_create_dir_text
);
402 createDirBtn
.setOnClickListener(this);
403 ((LinearLayout
) findViewById(R
.id
.linearLayout1
)).addView(
404 createDirBtn
, LayoutParams
.FILL_PARENT
,
405 LayoutParams
.WRAP_CONTENT
);
410 private void prepareStreamsToUpload() {
411 if (getIntent().getAction().equals(Intent
.ACTION_SEND
)) {
412 mStreamsToUpload
= new ArrayList
<Parcelable
>();
413 mStreamsToUpload
.add(getIntent().getParcelableExtra(
414 Intent
.EXTRA_STREAM
));
415 } else if (getIntent().getAction().equals(Intent
.ACTION_SEND_MULTIPLE
)) {
416 mStreamsToUpload
= getIntent().getParcelableArrayListExtra(
417 Intent
.EXTRA_STREAM
);
419 // unknow action inserted
420 throw new IllegalArgumentException("Unknown action given: "
421 + getIntent().getAction());
425 public void PartialupdateUpload(String fileLocalPath
, String filename
,
426 String filepath
, String contentType
, String contentLength
) {
427 ContentValues cv
= new ContentValues();
428 cv
.put(ProviderTableMeta
.FILE_NAME
, filename
);
429 cv
.put(ProviderTableMeta
.FILE_PATH
, filepath
);
430 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, fileLocalPath
);
431 cv
.put(ProviderTableMeta
.FILE_MODIFIED
,
432 WebdavUtils
.DISPLAY_DATE_FORMAT
.format(new java
.util
.Date()));
433 cv
.put(ProviderTableMeta
.FILE_CONTENT_TYPE
, contentType
);
434 cv
.put(ProviderTableMeta
.FILE_CONTENT_LENGTH
, contentLength
);
435 cv
.put(ProviderTableMeta
.FILE_ACCOUNT_OWNER
, mAccount
.name
);
436 Log
.d(TAG
, filename
+ " ++ " + filepath
+ " ++ " + contentLength
437 + " ++ " + contentType
+ " ++ " + fileLocalPath
);
438 if (!mParents
.empty()) {
439 Cursor c
= managedQuery(Uri
.withAppendedPath(
440 ProviderTableMeta
.CONTENT_URI_FILE
, mParents
.peek()), null
,
443 cv
.put(ProviderTableMeta
.FILE_PARENT
,
444 c
.getString(c
.getColumnIndex(ProviderTableMeta
._ID
)));
447 getContentResolver().insert(ProviderTableMeta
.CONTENT_URI_FILE
, cv
);
450 class BackgroundUploader
implements Runnable
{
451 private ArrayList
<Parcelable
> mUploadStreams
;
452 private Handler mHandler
;
453 private String mUploadPath
;
454 private boolean mCreateDir
;
456 public BackgroundUploader(String pathToUpload
,
457 ArrayList
<Parcelable
> streamsToUpload
, Handler handler
) {
458 mUploadStreams
= streamsToUpload
;
460 mUploadPath
= pathToUpload
.replace(" ", "%20");
464 public BackgroundUploader(String pathToUpload
,
465 ArrayList
<Parcelable
> streamsToUpload
, Handler handler
,
467 mUploadStreams
= streamsToUpload
;
469 mUploadPath
= pathToUpload
.replace(" ", "%20");
470 mCreateDir
= createDir
;
474 WebdavClient wdc
= new WebdavClient(Uri
.parse(mAccountManager
475 .getUserData(mAccount
, AccountAuthenticator
.KEY_OC_URL
)));
476 wdc
.setCredentials(mUsername
, mPassword
);
477 wdc
.allowUnsignedCertificates();
479 // create last directory in path if nessesary
481 wdc
.createDirectory(mUploadPath
);
484 for (int i
= 0; i
< mUploadStreams
.size(); ++i
) {
485 Uri uri
= (Uri
) mUploadStreams
.get(i
);
486 if (uri
.getScheme().equals("content")) {
487 final Cursor c
= getContentResolver()
488 .query((Uri
) mUploadStreams
.get(i
), null
, null
,
492 c
.getString(c
.getColumnIndex(Media
.DATA
)),
496 .getColumnIndex(Media
.DISPLAY_NAME
)),
497 c
.getString(c
.getColumnIndex(Media
.MIME_TYPE
)))) {
498 mHandler
.post(new Runnable() {
503 "Error while uploading file: "
505 .getColumnIndex(Media
.DISPLAY_NAME
)));
509 mHandler
.post(new Runnable() {
511 Uploader
.this.PartialupdateUpload(
513 .getColumnIndex(Media
.DATA
)),
515 .getColumnIndex(Media
.DISPLAY_NAME
)),
519 .getColumnIndex(Media
.DISPLAY_NAME
)),
521 .getColumnIndex(Media
.MIME_TYPE
)),
523 .getColumnIndex(Media
.SIZE
)));
527 } else if (uri
.getScheme().equals("file")) {
528 final File file
= new File(Uri
.decode(uri
.toString())
529 .replace(uri
.getScheme() + "://", ""));
530 FileNameMap fileNameMap
= URLConnection
.getFileNameMap();
531 String contentType
= fileNameMap
.getContentTypeFor(uri
533 if (contentType
== null
) {
534 contentType
= "text/plain";
536 if (!wdc
.putFile(file
.getAbsolutePath(), mUploadPath
+ "/"
537 + file
.getName(), contentType
)) {
538 mHandler
.post(new Runnable() {
540 Uploader
.this.onUploadComplete(
542 "Error while uploading file: "
550 mHandler
.post(new Runnable() {
552 Uploader
.this.onUploadComplete(true
, null
);