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