Added missing input after merge
[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 public void pushPath(String path) {
89 mDirectories.insert(path, 0);
90 }
91
92 public boolean popPath() {
93 mDirectories.remove(mDirectories.getItem(0));
94 return !mDirectories.isEmpty();
95 }
96
97 @Override
98 protected Dialog onCreateDialog(int id) {
99 Dialog dialog;
100 AlertDialog.Builder builder;
101 switch (id) {
102 case DIALOG_SETUP_ACCOUNT:
103 builder = new AlertDialog.Builder(this);
104 builder.setTitle(R.string.main_tit_accsetup);
105 builder.setMessage(R.string.main_wrn_accsetup);
106 builder.setCancelable(false);
107 builder.setPositiveButton(android.R.string.ok, this);
108 builder.setNegativeButton(android.R.string.cancel, this);
109 dialog = builder.create();
110 break;
111 case DIALOG_CREATE_DIR: {
112 builder = new Builder(this);
113 final EditText dirName = new EditText(getBaseContext());
114 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
115 builder.setView(dirName);
116 builder.setTitle(R.string.uploader_info_dirname);
117 int typed_color = getResources().getColor(R.color.setup_text_typed);
118 dirName.setTextColor(typed_color);
119
120 builder.setPositiveButton(android.R.string.ok,
121 new OnClickListener() {
122 public void onClick(DialogInterface dialog, int which) {
123 String s = dirName.getText().toString();
124 if (s.trim().length() == 0) {
125 dialog.cancel();
126 return;
127 }
128
129 String path = "";
130 for (int i = mDirectories.getCount() - 2; i >= 0; --i) {
131 path += "/" + mDirectories.getItem(i);
132 }
133 OCFile parent = mStorageManager.getFileByPath(path
134 + "/");
135 path += s + "/";
136 Thread thread = new Thread(new DirectoryCreator(
137 path, a));
138 thread.start();
139
140 OCFile new_file = new OCFile(path);
141 new_file.setMimetype("DIR");
142 new_file.setParentId(parent.getParentId());
143 mStorageManager.saveFile(new_file);
144
145 dialog.dismiss();
146 }
147 });
148 builder.setNegativeButton(R.string.common_cancel,
149 new OnClickListener() {
150 public void onClick(DialogInterface dialog, int which) {
151 dialog.cancel();
152 }
153 });
154 dialog = builder.create();
155 break;
156 }
157 default:
158 dialog = null;
159 }
160
161 return dialog;
162 }
163
164 @Override
165 public void onCreate(Bundle savedInstanceState) {
166 super.onCreate(savedInstanceState);
167
168 if (!accountsAreSetup()) {
169 showDialog(DIALOG_SETUP_ACCOUNT);
170 return;
171 }
172
173 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
174 setProgressBarIndeterminateVisibility(false);
175
176 setContentView(R.layout.files);
177
178 }
179
180 @Override
181 public boolean onOptionsItemSelected(MenuItem item) {
182 boolean retval = true;
183 switch (item.getItemId()) {
184 case R.id.createDirectoryItem: {
185 showDialog(DIALOG_CREATE_DIR);
186 break;
187 }
188 case R.id.startSync: {
189 Bundle bundle = new Bundle();
190 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
191 ContentResolver.requestSync(
192 AccountUtils.getCurrentOwnCloudAccount(this),
193 "org.owncloud", bundle);
194 break;
195 }
196 case R.id.action_upload: {
197 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
198 action = action.setType("*/*")
199 .addCategory(Intent.CATEGORY_OPENABLE);
200 startActivityForResult(
201 Intent.createChooser(action, "Upload file from..."),
202 ACTION_SELECT_FILE);
203 break;
204 }
205
206 case android.R.id.home: {
207 Intent i = new Intent(this, AccountSelectActivity.class);
208 startActivity(i);
209 finish();
210 break;
211 }
212 default:
213 retval = false;
214 }
215 return retval;
216 }
217
218 @Override
219 public void onBackPressed() {
220 if (mDirectories.getCount() == 1) {
221 finish();
222 return;
223 }
224 popPath();
225 ((FileListFragment) getSupportFragmentManager().findFragmentById(
226 R.id.fileList)).onNavigateUp();
227 }
228
229 @Override
230 public boolean onCreateOptionsMenu(Menu menu) {
231 MenuInflater inflater = getSherlock().getMenuInflater();
232 inflater.inflate(R.menu.menu, menu);
233 return true;
234 }
235
236 @Override
237 protected void onRestoreInstanceState(Bundle savedInstanceState) {
238 super.onRestoreInstanceState(savedInstanceState);
239 // Check, if there are ownCloud accounts
240 if (!accountsAreSetup()) {
241 showDialog(DIALOG_SETUP_ACCOUNT);
242 }
243 mDirs = savedInstanceState.getStringArray(KEY_DIR);
244 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
245 mDirectories.add("/");
246 if (mDirs != null)
247 for (String s : mDirs)
248 mDirectories.insert(s, 0);
249 }
250
251 @Override
252 protected void onSaveInstanceState(Bundle outState) {
253 super.onSaveInstanceState(outState);
254 if(mDirectories != null){
255 mDirs = new String[mDirectories.getCount()-1];
256 for (int j = mDirectories.getCount() - 2, i = 0; j >= 0; --j, ++i) {
257 mDirs[i] = mDirectories.getItem(j);
258 }
259 }
260 }
261
262 @Override
263 protected void onResume() {
264 super.onResume();
265 if (!accountsAreSetup()) {
266 showDialog(DIALOG_SETUP_ACCOUNT);
267 return;
268 }
269
270 IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);
271 syncBroadcastRevceiver = new SyncBroadcastReceiver();
272 registerReceiver(syncBroadcastRevceiver, f);
273
274 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
275 mDirectories.add("/");
276 if (mDirs != null) {
277 for (String s : mDirs)
278 mDirectories.insert(s, 0);
279 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
280 .findFragmentById(R.id.fileList);
281 if (fileListFramgent != null) fileListFramgent.listDirectory();
282 }
283
284 mStorageManager = new FileDataStorageManager(
285 AccountUtils.getCurrentOwnCloudAccount(this),
286 getContentResolver());
287 ActionBar action_bar = getSupportActionBar();
288 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
289 action_bar.setDisplayShowTitleEnabled(false);
290 action_bar.setListNavigationCallbacks(mDirectories, this);
291 action_bar.setDisplayHomeAsUpEnabled(true);
292 }
293
294 public void onActivityResult(int requestCode, int resultCode, Intent data) {
295 if (resultCode == RESULT_OK) {
296 if (requestCode == ACTION_SELECT_FILE) {
297 Uri selectedImageUri = data.getData();
298
299 String filemanagerstring = selectedImageUri.getPath();
300 String selectedImagePath = getPath(selectedImageUri);
301 String filepath;
302
303 if (selectedImagePath != null)
304 filepath = selectedImagePath;
305 else
306 filepath = filemanagerstring;
307
308 if (filepath == null) {
309 Log.e("FileDisplay", "Couldnt resolve path to file");
310 return;
311 }
312
313 Intent i = new Intent(this, FileUploader.class);
314 i.putExtra(FileUploader.KEY_ACCOUNT,
315 AccountUtils.getCurrentOwnCloudAccount(this));
316 String remotepath = new String();
317 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
318 remotepath += "/" + URLEncoder.encode(mDirectories.getItem(j));
319 }
320 if (!remotepath.endsWith("/"))
321 remotepath += "/";
322 remotepath += URLEncoder.encode(new File(filepath).getName());
323 Log.e("ASD", remotepath + "");
324
325 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
326 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
327 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, 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 }