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