e7ee4cc12a34c499ee7339aa05fba4fdf12e63e3
[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
80 private SyncBroadcastReceiver syncBroadcastRevceiver;
81
82 private static final int DIALOG_SETUP_ACCOUNT = 0;
83 private static final int DIALOG_CREATE_DIR = 1;
84
85 private static final int REQUEST_ACCOUNT_SETUP = 0;
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 // if (getSupportFragmentManager().findFragmentById(R.id.fileList) ==
176 // null)
177 setContentView(R.layout.files);
178
179 }
180
181 @Override
182 public boolean onOptionsItemSelected(MenuItem item) {
183 boolean retval = true;
184 switch (item.getItemId()) {
185 case R.id.settingsItem: {
186 Intent i = new Intent(this, Preferences.class);
187 startActivity(i);
188 break;
189 }
190 case R.id.createDirectoryItem: {
191 showDialog(DIALOG_CREATE_DIR);
192 break;
193 }
194 case R.id.startSync: {
195 Bundle bundle = new Bundle();
196 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
197 ContentResolver.requestSync(
198 AccountUtils.getCurrentOwnCloudAccount(this),
199 "org.owncloud", bundle);
200 break;
201 }
202 case R.id.action_upload: {
203 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
204 action = action.setType("*/*")
205 .addCategory(Intent.CATEGORY_OPENABLE);
206 startActivityForResult(
207 Intent.createChooser(action, "Upload file from..."),
208 ACTION_SELECT_FILE);
209 break;
210 }
211
212 case android.R.id.home: {
213 Intent i = new Intent(this, AccountSelectActivity.class);
214 startActivity(i);
215 finish();
216 break;
217 }
218 default:
219 retval = false;
220 }
221 return retval;
222 }
223
224 @Override
225 public void onBackPressed() {
226 if (mDirectories.getCount() == 1) {
227 finish();
228 return;
229 }
230 popPath();
231 ((FileListFragment) getSupportFragmentManager().findFragmentById(
232 R.id.fileList)).onNavigateUp();
233 }
234
235 @Override
236 public boolean onCreateOptionsMenu(Menu menu) {
237 MenuInflater inflater = getSherlock().getMenuInflater();
238 inflater.inflate(R.menu.menu, menu);
239 return true;
240 }
241
242 @Override
243 protected void onRestoreInstanceState(Bundle savedInstanceState) {
244 super.onRestoreInstanceState(savedInstanceState);
245 // Check, if there are ownCloud accounts
246 if (!accountsAreSetup()) {
247 showDialog(DIALOG_SETUP_ACCOUNT);
248 }
249 }
250
251 @Override
252 protected void onResume() {
253 super.onResume();
254 if (!accountsAreSetup()) {
255 showDialog(DIALOG_SETUP_ACCOUNT);
256 return;
257 }
258
259 IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);
260 syncBroadcastRevceiver = new SyncBroadcastReceiver();
261 registerReceiver(syncBroadcastRevceiver, f);
262
263 mDirectories = new CustomArrayAdapter<String>(this,
264 R.layout.sherlock_spinner_dropdown_item);
265 mDirectories.add("/");
266
267 mStorageManager = new FileDataStorageManager(
268 AccountUtils.getCurrentOwnCloudAccount(this),
269 getContentResolver());
270 ActionBar action_bar = getSupportActionBar();
271 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
272 action_bar.setDisplayShowTitleEnabled(false);
273 action_bar.setListNavigationCallbacks(mDirectories, this);
274 action_bar.setDisplayHomeAsUpEnabled(true);
275 }
276
277 public void onActivityResult(int requestCode, int resultCode, Intent data) {
278 Log.e("ASD", requestCode + " " + resultCode);
279 if (resultCode == RESULT_OK) {
280 if (requestCode == ACTION_SELECT_FILE) {
281 Uri selectedImageUri = data.getData();
282
283 String filemanagerstring = selectedImageUri.getPath();
284 String selectedImagePath = getPath(selectedImageUri);
285 String filepath;
286
287 if (selectedImagePath != null)
288 filepath = selectedImagePath;
289 else
290 filepath = filemanagerstring;
291
292 if (filepath == null) {
293 Log.e("FileDisplay", "Couldnt resolve path to file");
294 return;
295 }
296
297 Intent i = new Intent(this, FileUploader.class);
298 i.putExtra(FileUploader.KEY_ACCOUNT,
299 AccountUtils.getCurrentOwnCloudAccount(this));
300 String remotepath = new String();
301 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
302 remotepath += "/" + URLDecoder.decode(mDirectories.getItem(j));
303 }
304 if (!remotepath.endsWith("/"))
305 remotepath += "/";
306 remotepath += new File(filepath).getName();
307 Log.e("ASD", remotepath + "");
308
309 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
310 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
311 i.putExtra(FileUploader.KEY_UPLOAD_TYPE,
312 FileUploader.UPLOAD_SINGLE_FILE);
313 startService(i);
314 }
315 }
316 }
317
318 public String getPath(Uri uri) {
319 String[] projection = { MediaStore.Images.Media.DATA };
320 Cursor cursor = managedQuery(uri, projection, null, null, null);
321 if (cursor != null) {
322 int column_index = cursor
323 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
324 cursor.moveToFirst();
325 return cursor.getString(column_index);
326 } else
327 return null;
328 }
329
330 @Override
331 protected void onPause() {
332 super.onPause();
333 if (syncBroadcastRevceiver != null) {
334 unregisterReceiver(syncBroadcastRevceiver);
335 syncBroadcastRevceiver = null;
336 }
337
338 }
339
340 @Override
341 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
342 int i = itemPosition;
343 while (i-- != 0) {
344 onBackPressed();
345 }
346 return true;
347 }
348
349 private class DirectoryCreator implements Runnable {
350 private String mTargetPath;
351 private Account mAccount;
352 private AccountManager mAm;
353
354 public DirectoryCreator(String targetPath, Account account) {
355 mTargetPath = targetPath;
356 mAccount = account;
357 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
358 }
359
360 @Override
361 public void run() {
362 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
363 mAccount, AccountAuthenticator.KEY_OC_URL)));
364
365 String username = mAccount.name.substring(0,
366 mAccount.name.lastIndexOf('@'));
367 String password = mAm.getPassword(mAccount);
368
369 wdc.setCredentials(username, password);
370 wdc.allowUnsignedCertificates();
371 wdc.createDirectory(mTargetPath);
372 }
373
374 }
375
376 // Custom array adapter to override text colors
377 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
378
379 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
380 super(ctx, view);
381 }
382
383 public View getView(int position, View convertView, ViewGroup parent) {
384 View v = super.getView(position, convertView, parent);
385
386 ((TextView) v).setTextColor(getResources().getColorStateList(
387 android.R.color.white));
388 return v;
389 }
390
391 public View getDropDownView(int position, View convertView,
392 ViewGroup parent) {
393 View v = super.getDropDownView(position, convertView, parent);
394
395 ((TextView) v).setTextColor(getResources().getColorStateList(
396 android.R.color.white));
397
398 return v;
399 }
400
401 }
402
403 public void onClick(DialogInterface dialog, int which) {
404 // In any case - we won't need it anymore
405 dialog.dismiss();
406 switch (which) {
407 case DialogInterface.BUTTON_POSITIVE:
408 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
409 intent.putExtra("authorities",
410 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
411 startActivity(intent);
412 break;
413 case DialogInterface.BUTTON_NEGATIVE:
414 finish();
415 }
416
417 }
418
419 /**
420 * Checks, whether or not there are any ownCloud accounts setup.
421 *
422 * @return true, if there is at least one account.
423 */
424 private boolean accountsAreSetup() {
425 AccountManager accMan = AccountManager.get(this);
426 Account[] accounts = accMan
427 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
428 return accounts.length > 0;
429 }
430
431 private class SyncBroadcastReceiver extends BroadcastReceiver {
432 /**
433 * {@link BroadcastReceiver} to enable syncing feedback in UI
434 */
435 @Override
436 public void onReceive(Context context, Intent intent) {
437 boolean inProgress = intent.getBooleanExtra(
438 FileSyncService.IN_PROGRESS, false);
439 String account_name = intent
440 .getStringExtra(FileSyncService.ACCOUNT_NAME);
441 Log.d("FileDisplay", "sync of account " + account_name
442 + " is in_progress: " + inProgress);
443 setProgressBarIndeterminateVisibility(inProgress);
444 if (!inProgress) {
445 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()
446 .findFragmentById(R.id.fileList);
447 if (fileListFramgent != null)
448 fileListFramgent.populateFileList();
449 }
450 }
451
452 }
453
454 }