Merge branch 'master' of ssh://git@gitorious.org/owncloud/android-devel.git
[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 if (resultCode == RESULT_OK) {
294 if (requestCode == ACTION_SELECT_FILE) {
295 Uri selectedImageUri = data.getData();
296
297 String filemanagerstring = selectedImageUri.getPath();
298 String selectedImagePath = getPath(selectedImageUri);
299 String filepath;
300
301 if (selectedImagePath != null)
302 filepath = selectedImagePath;
303 else
304 filepath = filemanagerstring;
305
306 if (filepath == null) {
307 Log.e("FileDisplay", "Couldnt resolve path to file");
308 return;
309 }
310
311 Intent i = new Intent(this, FileUploader.class);
312 i.putExtra(FileUploader.KEY_ACCOUNT,
313 AccountUtils.getCurrentOwnCloudAccount(this));
314 String remotepath = new String();
315 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
316 remotepath += "/" + URLEncoder.encode(mDirectories.getItem(j));
317 }
318 if (!remotepath.endsWith("/"))
319 remotepath += "/";
320 remotepath += URLEncoder.encode(new File(filepath).getName());
321 Log.e("ASD", remotepath + "");
322
323 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
324 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
325 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
326 startService(i);
327 }
328 }
329 }
330
331 public String getPath(Uri uri) {
332 String[] projection = { MediaStore.Images.Media.DATA };
333 Cursor cursor = managedQuery(uri, projection, null, null, null);
334 if (cursor != null) {
335 int column_index = cursor
336 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
337 cursor.moveToFirst();
338 return cursor.getString(column_index);
339 } else
340 return null;
341 }
342
343 @Override
344 protected void onPause() {
345 super.onPause();
346 if (syncBroadcastRevceiver != null) {
347 unregisterReceiver(syncBroadcastRevceiver);
348 syncBroadcastRevceiver = null;
349 }
350
351 }
352
353 @Override
354 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
355 int i = itemPosition;
356 while (i-- != 0) {
357 onBackPressed();
358 }
359 return true;
360 }
361
362 private class DirectoryCreator implements Runnable {
363 private String mTargetPath;
364 private Account mAccount;
365 private AccountManager mAm;
366
367 public DirectoryCreator(String targetPath, Account account) {
368 mTargetPath = targetPath;
369 mAccount = account;
370 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
371 }
372
373 @Override
374 public void run() {
375 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
376 mAccount, AccountAuthenticator.KEY_OC_URL)));
377
378 String username = mAccount.name.substring(0,
379 mAccount.name.lastIndexOf('@'));
380 String password = mAm.getPassword(mAccount);
381
382 wdc.setCredentials(username, password);
383 wdc.allowUnsignedCertificates();
384 wdc.createDirectory(mTargetPath);
385 }
386
387 }
388
389 // Custom array adapter to override text colors
390 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
391
392 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
393 super(ctx, view);
394 }
395
396 public View getView(int position, View convertView, ViewGroup parent) {
397 View v = super.getView(position, convertView, parent);
398
399 ((TextView) v).setTextColor(getResources().getColorStateList(
400 android.R.color.white));
401 return v;
402 }
403
404 public View getDropDownView(int position, View convertView,
405 ViewGroup parent) {
406 View v = super.getDropDownView(position, convertView, parent);
407
408 ((TextView) v).setTextColor(getResources().getColorStateList(
409 android.R.color.white));
410
411 return v;
412 }
413
414 }
415
416 public void onClick(DialogInterface dialog, int which) {
417 // In any case - we won't need it anymore
418 dialog.dismiss();
419 switch (which) {
420 case DialogInterface.BUTTON_POSITIVE:
421 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
422 intent.putExtra("authorities",
423 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
424 startActivity(intent);
425 break;
426 case DialogInterface.BUTTON_NEGATIVE:
427 finish();
428 }
429
430 }
431
432 /**
433 * Checks, whether or not there are any ownCloud accounts setup.
434 *
435 * @return true, if there is at least one account.
436 */
437 private boolean accountsAreSetup() {
438 AccountManager accMan = AccountManager.get(this);
439 Account[] accounts = accMan
440 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
441 return accounts.length > 0;
442 }
443
444 private class SyncBroadcastReceiver extends BroadcastReceiver {
445 /**
446 * {@link BroadcastReceiver} to enable syncing feedback in UI
447 */
448 @Override
449 public void onReceive(Context context, Intent intent) {
450 boolean inProgress = intent.getBooleanExtra(
451 FileSyncService.IN_PROGRESS, false);
452 String account_name = intent
453 .getStringExtra(FileSyncService.ACCOUNT_NAME);
454 Log.d("FileDisplay", "sync of account " + account_name
455 + " is in_progress: " + inProgress);
456 setProgressBarIndeterminateVisibility(inProgress);
457 if (!inProgress) {
458 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
459 .findFragmentById(R.id.fileList);
460 if (fileListFramgent != null)
461 fileListFramgent.listDirectory();
462 }
463 }
464
465 }
466
467 }