Refactored app name in strings.xml
[pub/Android/ownCloud.git] / src / com / owncloud / android / Uploader.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18 package com.owncloud.android;
19
20 import java.io.File;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Stack;
26 import java.util.Vector;
27
28 import com.owncloud.android.authenticator.AccountAuthenticator;
29 import com.owncloud.android.datamodel.DataStorageManager;
30 import com.owncloud.android.datamodel.FileDataStorageManager;
31 import com.owncloud.android.datamodel.OCFile;
32 import com.owncloud.android.files.services.FileUploader;
33 import com.owncloud.android.network.OwnCloudClientUtils;
34
35 import android.accounts.Account;
36 import android.accounts.AccountManager;
37 import android.app.AlertDialog;
38 import android.app.AlertDialog.Builder;
39 import android.app.Dialog;
40 import android.app.ListActivity;
41 import android.app.ProgressDialog;
42 import android.content.Context;
43 import android.content.DialogInterface;
44 import android.content.DialogInterface.OnCancelListener;
45 import android.content.DialogInterface.OnClickListener;
46 import android.content.Intent;
47 import android.database.Cursor;
48 import android.net.Uri;
49 import android.os.Bundle;
50 import android.os.Parcelable;
51 import android.provider.MediaStore.Images.Media;
52 import android.util.Log;
53 import android.view.View;
54 import android.view.Window;
55 import android.widget.AdapterView;
56 import android.widget.AdapterView.OnItemClickListener;
57 import android.widget.Button;
58 import android.widget.EditText;
59 import android.widget.SimpleAdapter;
60 import android.widget.Toast;
61
62 import com.owncloud.android.R;
63 import eu.alefzero.webdav.WebdavClient;
64
65 /**
66 * This can be used to upload things to an ownCloud instance.
67 *
68 * @author Bartek Przybylski
69 *
70 */
71 public class Uploader extends ListActivity implements OnItemClickListener, android.view.View.OnClickListener {
72 private static final String TAG = "ownCloudUploader";
73
74 private Account mAccount;
75 private AccountManager mAccountManager;
76 private Stack<String> mParents;
77 private ArrayList<Parcelable> mStreamsToUpload;
78 private boolean mCreateDir;
79 private String mUploadPath;
80 private static final String[] CONTENT_PROJECTION = { Media.DATA, Media.DISPLAY_NAME, Media.MIME_TYPE, Media.SIZE };
81 private DataStorageManager mStorageManager;
82 private OCFile mFile;
83
84 private final static int DIALOG_NO_ACCOUNT = 0;
85 private final static int DIALOG_WAITING = 1;
86 private final static int DIALOG_NO_STREAM = 2;
87 private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
88 //private final static int DIALOG_GET_DIRNAME = 4;
89
90 private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
91
92 @Override
93 protected void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
96 mParents = new Stack<String>();
97 mParents.add("");
98 /*if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
99 prepareStreamsToUpload();*/
100 if (prepareStreamsToUpload()) {
101 mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
102 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
103 if (accounts.length == 0) {
104 Log.i(TAG, "No ownCloud account is available");
105 showDialog(DIALOG_NO_ACCOUNT);
106 } else if (accounts.length > 1) {
107 Log.i(TAG, "More then one ownCloud is available");
108 showDialog(DIALOG_MULTIPLE_ACCOUNT);
109 } else {
110 mAccount = accounts[0];
111 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
112 populateDirectoryList();
113 }
114 } else {
115 showDialog(DIALOG_NO_STREAM);
116 }
117 }
118
119 @Override
120 protected Dialog onCreateDialog(final int id) {
121 final AlertDialog.Builder builder = new Builder(this);
122 switch (id) {
123 case DIALOG_WAITING:
124 ProgressDialog pDialog = new ProgressDialog(this);
125 pDialog.setIndeterminate(false);
126 pDialog.setCancelable(false);
127 pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));
128 return pDialog;
129 case DIALOG_NO_ACCOUNT:
130 builder.setIcon(android.R.drawable.ic_dialog_alert);
131 builder.setTitle(R.string.uploader_wrn_no_account_title);
132 builder.setMessage(String.format(getString(R.string.uploader_wrn_no_account_text), getString(R.string.app_name)));
133 builder.setCancelable(false);
134 builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
135 @Override
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("android.settings.ADD_ACCOUNT_SETTINGS");
144 intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
145 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
146 } else {
147 // since in API7 there is no direct call for
148 // account setup, so we need to
149 // show our own AccountSetupAcricity, get
150 // desired results and setup
151 // everything for ourself
152 Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
153 startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
154 }
155 }
156 });
157 builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
158 @Override
159 public void onClick(DialogInterface dialog, int which) {
160 finish();
161 }
162 });
163 return builder.create();
164 /*case DIALOG_GET_DIRNAME:
165 final EditText dirName = new EditText(getBaseContext());
166 builder.setView(dirName);
167 builder.setTitle(R.string.uploader_info_dirname);
168 String pathToUpload;
169 if (mParents.empty()) {
170 pathToUpload = "/";
171 } else {
172 mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), null,
173 null, null, null);
174 mCursor.moveToFirst();
175 pathToUpload = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH))
176 + mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_NAME)).replace(" ", "%20"); // TODO don't make this ; use WebdavUtils.encode in the right moment
177 }
178 a a = new a(pathToUpload, dirName);
179 builder.setPositiveButton(R.string.common_ok, a);
180 builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
181 public void onClick(DialogInterface dialog, int which) {
182 dialog.cancel();
183 }
184 });
185 return builder.create();*/
186 case DIALOG_MULTIPLE_ACCOUNT:
187 CharSequence ac[] = new CharSequence[mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE).length];
188 for (int i = 0; i < ac.length; ++i) {
189 ac[i] = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[i].name;
190 }
191 builder.setTitle(R.string.common_choose_account);
192 builder.setItems(ac, new OnClickListener() {
193 @Override
194 public void onClick(DialogInterface dialog, int which) {
195 mAccount = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];
196 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
197 populateDirectoryList();
198 }
199 });
200 builder.setCancelable(true);
201 builder.setOnCancelListener(new OnCancelListener() {
202 @Override
203 public void onCancel(DialogInterface dialog) {
204 dialog.cancel();
205 finish();
206 }
207 });
208 return builder.create();
209 case DIALOG_NO_STREAM:
210 builder.setIcon(android.R.drawable.ic_dialog_alert);
211 builder.setTitle(R.string.uploader_wrn_no_content_title);
212 builder.setMessage(R.string.uploader_wrn_no_content_text);
213 builder.setCancelable(false);
214 builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
215 @Override
216 public void onClick(DialogInterface dialog, int which) {
217 finish();
218 }
219 });
220 return builder.create();
221 default:
222 throw new IllegalArgumentException("Unknown dialog id: " + id);
223 }
224 }
225
226 class a implements OnClickListener {
227 String mPath;
228 EditText mDirname;
229
230 public a(String path, EditText dirname) {
231 mPath = path;
232 mDirname = dirname;
233 }
234
235 @Override
236 public void onClick(DialogInterface dialog, int which) {
237 Uploader.this.mUploadPath = mPath + mDirname.getText().toString();
238 Uploader.this.mCreateDir = true;
239 uploadFiles();
240 }
241 }
242
243 @Override
244 public void onBackPressed() {
245
246 if (mParents.size() <= 1) {
247 super.onBackPressed();
248 return;
249 } else {
250 mParents.pop();
251 populateDirectoryList();
252 }
253 }
254
255 @Override
256 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
257 // click on folder in the list
258 Log.d(TAG, "on item click");
259 Vector<OCFile> tmpfiles = mStorageManager.getDirectoryContent(mFile);
260 if (tmpfiles == null) return;
261 // filter on dirtype
262 Vector<OCFile> files = new Vector<OCFile>();
263 for (OCFile f : tmpfiles)
264 if (f.isDirectory())
265 files.add(f);
266 if (files.size() < position) {
267 throw new IndexOutOfBoundsException("Incorrect item selected");
268 }
269 mParents.push(files.get(position).getFileName());
270 populateDirectoryList();
271 }
272
273 @Override
274 public void onClick(View v) {
275 // click on button
276 switch (v.getId()) {
277 case R.id.uploader_choose_folder:
278 mUploadPath = ""; // first element in mParents is root dir, represented by ""; init mUploadPath with "/" results in a "//" prefix
279 for (String p : mParents)
280 mUploadPath += p + OCFile.PATH_SEPARATOR;
281 Log.d(TAG, "Uploading file to dir " + mUploadPath);
282
283 uploadFiles();
284
285 break;
286 /*case android.R.id.button1: // dynamic action for create aditional dir
287 showDialog(DIALOG_GET_DIRNAME);
288 break;*/
289 default:
290 throw new IllegalArgumentException("Wrong element clicked");
291 }
292 }
293
294 @Override
295 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
296 super.onActivityResult(requestCode, resultCode, data);
297 Log.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
298 if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
299 dismissDialog(DIALOG_NO_ACCOUNT);
300 if (resultCode == RESULT_CANCELED) {
301 finish();
302 }
303 Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);
304 if (accounts.length == 0) {
305 showDialog(DIALOG_NO_ACCOUNT);
306 } else {
307 // there is no need for checking for is there more then one
308 // account at this point
309 // since account setup can set only one account at time
310 mAccount = accounts[0];
311 populateDirectoryList();
312 }
313 }
314 }
315
316 private void populateDirectoryList() {
317 setContentView(R.layout.uploader_layout);
318
319 String full_path = "";
320 for (String a : mParents)
321 full_path += a + "/";
322
323 Log.d(TAG, "Populating view with content of : " + full_path);
324
325 mFile = mStorageManager.getFileByPath(full_path);
326 if (mFile != null) {
327 Vector<OCFile> files = mStorageManager.getDirectoryContent(mFile);
328 if (files != null) {
329 List<HashMap<String, Object>> data = new LinkedList<HashMap<String,Object>>();
330 for (OCFile f : files) {
331 HashMap<String, Object> h = new HashMap<String, Object>();
332 if (f.isDirectory()) {
333 h.put("dirname", f.getFileName());
334 data.add(h);
335 }
336 }
337 SimpleAdapter sa = new SimpleAdapter(this,
338 data,
339 R.layout.uploader_list_item_layout,
340 new String[] {"dirname"},
341 new int[] {R.id.textView1});
342 setListAdapter(sa);
343 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
344 btn.setOnClickListener(this);
345 getListView().setOnItemClickListener(this);
346 }
347 }
348 /*
349 mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI, null, ProviderTableMeta.FILE_NAME
350 + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { "/", mAccount.name }, null);
351
352 if (mCursor.moveToFirst()) {
353 mCursor = managedQuery(
354 ProviderMeta.ProviderTableMeta.CONTENT_URI,
355 null,
356 ProviderTableMeta.FILE_CONTENT_TYPE + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND "
357 + ProviderTableMeta.FILE_PARENT + "=?",
358 new String[] { "DIR", mAccount.name,
359 mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta._ID)) }, null);
360
361 ListView lv = getListView();
362 lv.setOnItemClickListener(this);
363 SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.uploader_list_item_layout, mCursor,
364 new String[] { ProviderTableMeta.FILE_NAME }, new int[] { R.id.textView1 });
365 setListAdapter(sca);
366 Button btn = (Button) findViewById(R.id.uploader_choose_folder);
367 btn.setOnClickListener(this);
368 /*
369 * disable this until new server interaction service wont be created
370 * // insert create new directory for multiple items uploading if
371 * (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
372 * Button createDirBtn = new Button(this);
373 * createDirBtn.setId(android.R.id.button1);
374 * createDirBtn.setText(R.string.uploader_btn_create_dir_text);
375 * createDirBtn.setOnClickListener(this); ((LinearLayout)
376 * findViewById(R.id.linearLayout1)).addView( createDirBtn,
377 * LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); }
378 *
379 }*/
380 }
381
382 private boolean prepareStreamsToUpload() {
383 if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
384 mStreamsToUpload = new ArrayList<Parcelable>();
385 mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
386 } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
387 mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
388 }
389 return (mStreamsToUpload != null && mStreamsToUpload.get(0) != null);
390 }
391
392 public void uploadFiles() {
393 try {
394 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
395
396 // create last directory in path if necessary
397 if (mCreateDir) {
398 wdc.createDirectory(mUploadPath);
399 }
400
401 String[] local = new String[mStreamsToUpload.size()], remote = new String[mStreamsToUpload.size()];
402
403 for (int i = 0; i < mStreamsToUpload.size(); ++i) {
404 Uri uri = (Uri) mStreamsToUpload.get(i);
405 if (uri.getScheme().equals("content")) {
406 Cursor c = getContentResolver().query((Uri) mStreamsToUpload.get(i),
407 CONTENT_PROJECTION,
408 null,
409 null,
410 null);
411
412 if (!c.moveToFirst())
413 continue;
414
415 final String display_name = c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),
416 data = c.getString(c.getColumnIndex(Media.DATA));
417 local[i] = data;
418 remote[i] = mUploadPath + display_name;
419 } else if (uri.getScheme().equals("file")) {
420 final File file = new File(Uri.decode(uri.toString()).replace(uri.getScheme() + "://", ""));
421 local[i] = file.getAbsolutePath();
422 remote[i] = mUploadPath + file.getName();
423 }
424
425 }
426 Intent intent = new Intent(getApplicationContext(), FileUploader.class);
427 intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
428 intent.putExtra(FileUploader.KEY_LOCAL_FILE, local);
429 intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote);
430 intent.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
431 startService(intent);
432 finish();
433
434 } catch (SecurityException e) {
435 String message = String.format(getString(R.string.uploader_error_forbidden_content), getString(R.string.app_name));
436 Toast.makeText(this, message, Toast.LENGTH_LONG).show();
437 }
438 }
439
440 }