Filelisting using intents and OCFile.getId() instead of string matching
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 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
19 package eu.alefzero.owncloud.ui.activity;
20
21 import java.io.File;
22 import java.net.URLDecoder;
23 import android.accounts.Account;
24 import android.accounts.AccountManager;
25 import android.app.AlertDialog;
26 import android.app.AlertDialog.Builder;
27 import android.app.Dialog;
28 import android.content.BroadcastReceiver;
29 import android.content.ContentResolver;
30 import android.content.Context;
31 import android.content.DialogInterface;
32 import android.content.DialogInterface.OnClickListener;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.database.Cursor;
36 import android.net.Uri;
37 import android.os.Bundle;
38 import android.provider.MediaStore;
39 import android.util.Log;
40 import android.view.View;
41 import android.view.ViewGroup;
42 import android.widget.ArrayAdapter;
43 import android.widget.EditText;
44 import android.widget.TextView;
45
46 import com.actionbarsherlock.app.ActionBar;
47 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
48 import com.actionbarsherlock.app.SherlockFragmentActivity;
49 import com.actionbarsherlock.view.Menu;
50 import com.actionbarsherlock.view.MenuInflater;
51 import com.actionbarsherlock.view.MenuItem;
52 import com.actionbarsherlock.view.Window;
53
54 import eu.alefzero.owncloud.AccountUtils;
55 import eu.alefzero.owncloud.R;
56 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
57 import eu.alefzero.owncloud.datamodel.DataStorageManager;
58 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
59 import eu.alefzero.owncloud.datamodel.OCFile;
60 import eu.alefzero.owncloud.files.services.FileUploader;
61 import eu.alefzero.owncloud.syncadapter.FileSyncService;
62 import eu.alefzero.owncloud.ui.fragment.FileListFragment;
63 import eu.alefzero.webdav.WebdavClient;
64
65 /**
66 * Displays, what files the user has available in his ownCloud.
67 *
68 * @author Bartek Przybylski
69 *
70 */
71
72 public class FileDisplayActivity extends SherlockFragmentActivity implements
73 OnNavigationListener, OnClickListener {
74 private ArrayAdapter<String> mDirectories;
75 private DataStorageManager mStorageManager;
76 private String[] mDirs = null;
77
78 private SyncBroadcastReceiver syncBroadcastRevceiver;
79
80 private static final String KEY_DIR = "DIR";
81
82 private static final int DIALOG_SETUP_ACCOUNT = 0;
83 private static final int DIALOG_CREATE_DIR = 1;
84 private static final int ACTION_SELECT_FILE = 1;
85
86 public void pushPath(String path) {
87 mDirectories.insert(path, 0);
88 }
89
90 public boolean popPath() {
91 mDirectories.remove(mDirectories.getItem(0));
92 return !mDirectories.isEmpty();
93 }
94
95 @Override
96 protected Dialog onCreateDialog(int id) {
97 Dialog dialog;
98 AlertDialog.Builder builder;
99 switch (id) {
100 case DIALOG_SETUP_ACCOUNT:
101 builder = new AlertDialog.Builder(this);
102 builder.setTitle(R.string.main_tit_accsetup);
103 builder.setMessage(R.string.main_wrn_accsetup);
104 builder.setCancelable(false);
105 builder.setPositiveButton(android.R.string.ok, this);
106 builder.setNegativeButton(android.R.string.cancel, this);
107 dialog = builder.create();
108 break;
109 case DIALOG_CREATE_DIR: {
110 builder = new Builder(this);
111 final EditText dirName = new EditText(getBaseContext());
112 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
113 builder.setView(dirName);
114 builder.setTitle(R.string.uploader_info_dirname);
115 int typed_color = getResources().getColor(R.color.setup_text_typed);
116 dirName.setTextColor(typed_color);
117
118 builder.setPositiveButton(android.R.string.ok,
119 new OnClickListener() {
120 public void onClick(DialogInterface dialog, int which) {
121 String s = dirName.getText().toString();
122 if (s.trim().length() == 0) {
123 dialog.cancel();
124 return;
125 }
126
127 String path = "";
128 for (int i = mDirectories.getCount() - 2; i >= 0; --i) {
129 path += "/" + mDirectories.getItem(i);
130 }
131 OCFile parent = mStorageManager.getFileByPath(path
132 + "/");
133 path += s + "/";
134 Thread thread = new Thread(new DirectoryCreator(
135 path, a));
136 thread.start();
137
138 OCFile new_file = new OCFile(path);
139 new_file.setMimetype("DIR");
140 new_file.setParentId(parent.getParentId());
141 mStorageManager.saveFile(new_file);
142
143 dialog.dismiss();
144 }
145 });
146 builder.setNegativeButton(R.string.common_cancel,
147 new OnClickListener() {
148 public void onClick(DialogInterface dialog, int which) {
149 dialog.cancel();
150 }
151 });
152 dialog = builder.create();
153 break;
154 }
155 default:
156 dialog = null;
157 }
158
159 return dialog;
160 }
161
162 @Override
163 public void onCreate(Bundle savedInstanceState) {
164 super.onCreate(savedInstanceState);
165
166 if (!accountsAreSetup()) {
167 showDialog(DIALOG_SETUP_ACCOUNT);
168 return;
169 }
170
171 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
172 setProgressBarIndeterminateVisibility(false);
173
174 setContentView(R.layout.files);
175
176 }
177
178 @Override
179 public boolean onOptionsItemSelected(MenuItem item) {
180 boolean retval = true;
181 switch (item.getItemId()) {
182 case R.id.createDirectoryItem: {
183 showDialog(DIALOG_CREATE_DIR);
184 break;
185 }
186 case R.id.startSync: {
187 Bundle bundle = new Bundle();
188 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
189 ContentResolver.requestSync(
190 AccountUtils.getCurrentOwnCloudAccount(this),
191 "org.owncloud", bundle);
192 break;
193 }
194 case R.id.action_upload: {
195 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
196 action = action.setType("*/*")
197 .addCategory(Intent.CATEGORY_OPENABLE);
198 startActivityForResult(
199 Intent.createChooser(action, "Upload file from..."),
200 ACTION_SELECT_FILE);
201 break;
202 }
203
204 case android.R.id.home: {
205 Intent i = new Intent(this, AccountSelectActivity.class);
206 startActivity(i);
207 finish();
208 break;
209 }
210 default:
211 retval = false;
212 }
213 return retval;
214 }
215
216 @Override
217 public void onBackPressed() {
218 if (mDirectories.getCount() == 1) {
219 finish();
220 return;
221 }
222 popPath();
223 ((FileListFragment) getSupportFragmentManager().findFragmentById(
224 R.id.fileList)).onNavigateUp();
225 }
226
227 @Override
228 public boolean onCreateOptionsMenu(Menu menu) {
229 MenuInflater inflater = getSherlock().getMenuInflater();
230 inflater.inflate(R.menu.menu, menu);
231 return true;
232 }
233
234 @Override
235 protected void onRestoreInstanceState(Bundle savedInstanceState) {
236 super.onRestoreInstanceState(savedInstanceState);
237 // Check, if there are ownCloud accounts
238 if (!accountsAreSetup()) {
239 showDialog(DIALOG_SETUP_ACCOUNT);
240 }
241 mDirs = savedInstanceState.getStringArray(KEY_DIR);
242 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
243 mDirectories.add("/");
244 if (mDirs != null)
245 for (String s : mDirs)
246 mDirectories.insert(s, 0);
247 }
248
249 @Override
250 protected void onSaveInstanceState(Bundle outState) {
251 super.onSaveInstanceState(outState);
252 if(mDirectories != null){
253 mDirs = new String[mDirectories.getCount()-1];
254 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
255 mDirs[i] = mDirectories.getItem(j);
256 }
257 }
258 }
259
260 @Override
261 protected void onResume() {
262 super.onResume();
263 if (!accountsAreSetup()) {
264 showDialog(DIALOG_SETUP_ACCOUNT);
265 return;
266 }
267
268 IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);
269 syncBroadcastRevceiver = new SyncBroadcastReceiver();
270 registerReceiver(syncBroadcastRevceiver, f);
271
272 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
273 mDirectories.add("/");
274 if (mDirs != null) {
275 for (String s : mDirs)
276 mDirectories.insert(s, 0);
277 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
278 .findFragmentById(R.id.fileList);
279 if (fileListFramgent != null) fileListFramgent.listDirectory();
280 }
281
282 mStorageManager = new FileDataStorageManager(
283 AccountUtils.getCurrentOwnCloudAccount(this),
284 getContentResolver());
285 ActionBar action_bar = getSupportActionBar();
286 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
287 action_bar.setDisplayShowTitleEnabled(false);
288 action_bar.setListNavigationCallbacks(mDirectories, this);
289 action_bar.setDisplayHomeAsUpEnabled(true);
290 }
291
292 public void onActivityResult(int requestCode, int resultCode, Intent data) {
293 Log.e("ASD", requestCode + " " + resultCode);
294 if (resultCode == RESULT_OK) {
295 if (requestCode == ACTION_SELECT_FILE) {
296 Uri selectedImageUri = data.getData();
297
298 String filemanagerstring = selectedImageUri.getPath();
299 String selectedImagePath = getPath(selectedImageUri);
300 String filepath;
301
302 if (selectedImagePath != null)
303 filepath = selectedImagePath;
304 else
305 filepath = filemanagerstring;
306
307 if (filepath == null) {
308 Log.e("FileDisplay", "Couldnt resolve path to file");
309 return;
310 }
311
312 Intent i = new Intent(this, FileUploader.class);
313 i.putExtra(FileUploader.KEY_ACCOUNT,
314 AccountUtils.getCurrentOwnCloudAccount(this));
315 String remotepath = new String();
316 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
317 remotepath += "/" + URLDecoder.decode(mDirectories.getItem(j));
318 }
319 if (!remotepath.endsWith("/"))
320 remotepath += "/";
321 remotepath += new File(filepath).getName();
322 Log.e("ASD", remotepath + "");
323
324 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
325 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
326 i.putExtra(FileUploader.KEY_UPLOAD_TYPE,
327 FileUploader.UPLOAD_SINGLE_FILE);
328 startService(i);
329 }
330 }
331 }
332
333 public String getPath(Uri uri) {
334 String[] projection = { MediaStore.Images.Media.DATA };
335 Cursor cursor = managedQuery(uri, projection, null, null, null);
336 if (cursor != null) {
337 int column_index = cursor
338 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
339 cursor.moveToFirst();
340 return cursor.getString(column_index);
341 } else
342 return null;
343 }
344
345 @Override
346 protected void onPause() {
347 super.onPause();
348 if (syncBroadcastRevceiver != null) {
349 unregisterReceiver(syncBroadcastRevceiver);
350 syncBroadcastRevceiver = null;
351 }
352
353 }
354
355 @Override
356 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
357 int i = itemPosition;
358 while (i-- != 0) {
359 onBackPressed();
360 }
361 return true;
362 }
363
364 private class DirectoryCreator implements Runnable {
365 private String mTargetPath;
366 private Account mAccount;
367 private AccountManager mAm;
368
369 public DirectoryCreator(String targetPath, Account account) {
370 mTargetPath = targetPath;
371 mAccount = account;
372 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
373 }
374
375 @Override
376 public void run() {
377 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
378 mAccount, AccountAuthenticator.KEY_OC_URL)));
379
380 String username = mAccount.name.substring(0,
381 mAccount.name.lastIndexOf('@'));
382 String password = mAm.getPassword(mAccount);
383
384 wdc.setCredentials(username, password);
385 wdc.allowUnsignedCertificates();
386 wdc.createDirectory(mTargetPath);
387 }
388
389 }
390
391 // Custom array adapter to override text colors
392 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
393
394 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
395 super(ctx, view);
396 }
397
398 public View getView(int position, View convertView, ViewGroup parent) {
399 View v = super.getView(position, convertView, parent);
400
401 ((TextView) v).setTextColor(getResources().getColorStateList(
402 android.R.color.white));
403 return v;
404 }
405
406 public View getDropDownView(int position, View convertView,
407 ViewGroup parent) {
408 View v = super.getDropDownView(position, convertView, parent);
409
410 ((TextView) v).setTextColor(getResources().getColorStateList(
411 android.R.color.white));
412
413 return v;
414 }
415
416 }
417
418 public void onClick(DialogInterface dialog, int which) {
419 // In any case - we won't need it anymore
420 dialog.dismiss();
421 switch (which) {
422 case DialogInterface.BUTTON_POSITIVE:
423 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
424 intent.putExtra("authorities",
425 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
426 startActivity(intent);
427 break;
428 case DialogInterface.BUTTON_NEGATIVE:
429 finish();
430 }
431
432 }
433
434 /**
435 * Checks, whether or not there are any ownCloud accounts setup.
436 *
437 * @return true, if there is at least one account.
438 */
439 private boolean accountsAreSetup() {
440 AccountManager accMan = AccountManager.get(this);
441 Account[] accounts = accMan
442 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
443 return accounts.length > 0;
444 }
445
446 private class SyncBroadcastReceiver extends BroadcastReceiver {
447 /**
448 * {@link BroadcastReceiver} to enable syncing feedback in UI
449 */
450 @Override
451 public void onReceive(Context context, Intent intent) {
452 boolean inProgress = intent.getBooleanExtra(
453 FileSyncService.IN_PROGRESS, false);
454 String account_name = intent
455 .getStringExtra(FileSyncService.ACCOUNT_NAME);
456 Log.d("FileDisplay", "sync of account " + account_name
457 + " is in_progress: " + inProgress);
458 setProgressBarIndeterminateVisibility(inProgress);
459 if (!inProgress) {
460 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
461 .findFragmentById(R.id.fileList);
462 if (fileListFramgent != null)
463 fileListFramgent.listDirectory();
464 }
465 }
466
467 }
468
469 }