UploadFileActivity protected agains access to non-existing account
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17 package com.owncloud.android.ui.preview;
18
19 import android.app.Dialog;
20 import android.app.ProgressDialog;
21 import android.content.BroadcastReceiver;
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.content.ServiceConnection;
27 import android.os.Bundle;
28 import android.os.IBinder;
29 import android.support.v4.view.ViewPager;
30 import android.view.MotionEvent;
31 import android.view.View;
32 import android.view.View.OnTouchListener;
33
34 import com.actionbarsherlock.app.ActionBar;
35 import com.actionbarsherlock.view.MenuItem;
36 import com.actionbarsherlock.view.Window;
37 import com.owncloud.android.datamodel.DataStorageManager;
38 import com.owncloud.android.datamodel.FileDataStorageManager;
39 import com.owncloud.android.datamodel.OCFile;
40 import com.owncloud.android.files.services.FileDownloader;
41 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
42 import com.owncloud.android.files.services.FileUploader;
43 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
44 import com.owncloud.android.ui.activity.FileActivity;
45 import com.owncloud.android.ui.activity.FileDisplayActivity;
46 import com.owncloud.android.ui.fragment.FileFragment;
47 import com.owncloud.android.AccountUtils;
48 import com.owncloud.android.Log_OC;
49 import com.owncloud.android.R;
50
51 /**
52 * Holds a swiping galley where image files contained in an ownCloud directory are shown
53 *
54 * @author David A. Velasco
55 */
56 public class PreviewImageActivity extends FileActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
57
58 public static final int DIALOG_SHORT_WAIT = 0;
59
60 public static final String TAG = PreviewImageActivity.class.getSimpleName();
61
62 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
63 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
64
65 private DataStorageManager mStorageManager;
66
67 private ViewPager mViewPager;
68 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
69
70 private FileDownloaderBinder mDownloaderBinder = null;
71 private ServiceConnection mDownloadConnection, mUploadConnection = null;
72 private FileUploaderBinder mUploaderBinder = null;
73
74 private boolean mRequestWaitingForBinder;
75
76 private DownloadFinishReceiver mDownloadFinishReceiver;
77
78 private boolean mFullScreen;
79
80
81 @Override
82 protected void onCreate(Bundle savedInstanceState) {
83 super.onCreate(savedInstanceState);
84
85 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
86 setContentView(R.layout.preview_image_activity);
87
88 ActionBar actionBar = getSupportActionBar();
89 actionBar.setDisplayHomeAsUpEnabled(true);
90 actionBar.hide();
91
92 mFullScreen = true;
93 if (savedInstanceState != null) {
94 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
95 } else {
96 mRequestWaitingForBinder = false;
97 }
98 }
99
100 private void initViewPager() {
101 OCFile parentFolder = mStorageManager.getFileById(getFile().getParentId());
102 if (parentFolder == null) {
103 // should not be necessary
104 parentFolder = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
105 }
106 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder, getAccount(), mStorageManager);
107 mViewPager = (ViewPager) findViewById(R.id.fragmentPager);
108 int position = mPreviewImagePagerAdapter.getFilePosition(getFile());
109 position = (position >= 0) ? position : 0;
110 mViewPager.setAdapter(mPreviewImagePagerAdapter);
111 mViewPager.setOnPageChangeListener(this);
112 mViewPager.setCurrentItem(position);
113 if (position == 0 && !getFile().isDown()) {
114 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
115 mRequestWaitingForBinder = true;
116 }
117 }
118
119
120 @Override
121 public void onStart() {
122 super.onStart();
123 mDownloadConnection = new PreviewImageServiceConnection();
124 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
125 mUploadConnection = new PreviewImageServiceConnection();
126 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
127 }
128
129 @Override
130 protected void onSaveInstanceState(Bundle outState) {
131 super.onSaveInstanceState(outState);
132 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
133 }
134
135
136 /** Defines callbacks for service binding, passed to bindService() */
137 private class PreviewImageServiceConnection implements ServiceConnection {
138
139 @Override
140 public void onServiceConnected(ComponentName component, IBinder service) {
141
142 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
143 mDownloaderBinder = (FileDownloaderBinder) service;
144 if (mRequestWaitingForBinder) {
145 mRequestWaitingForBinder = false;
146 Log_OC.d(TAG, "Simulating reselection of current page after connection of download binder");
147 onPageSelected(mViewPager.getCurrentItem());
148 }
149
150 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
151 Log_OC.d(TAG, "Upload service connected");
152 mUploaderBinder = (FileUploaderBinder) service;
153 } else {
154 return;
155 }
156
157 }
158
159 @Override
160 public void onServiceDisconnected(ComponentName component) {
161 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
162 Log_OC.d(TAG, "Download service suddenly disconnected");
163 mDownloaderBinder = null;
164 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
165 Log_OC.d(TAG, "Upload service suddenly disconnected");
166 mUploaderBinder = null;
167 }
168 }
169 };
170
171
172 @Override
173 public void onStop() {
174 super.onStop();
175 if (mDownloadConnection != null) {
176 unbindService(mDownloadConnection);
177 mDownloadConnection = null;
178 }
179 if (mUploadConnection != null) {
180 unbindService(mUploadConnection);
181 mUploadConnection = null;
182 }
183 }
184
185
186 @Override
187 public void onDestroy() {
188 super.onDestroy();
189 }
190
191
192 @Override
193 public boolean onOptionsItemSelected(MenuItem item) {
194 boolean returnValue = false;
195
196 switch(item.getItemId()){
197 case android.R.id.home:
198 backToDisplayActivity();
199 returnValue = true;
200 break;
201 default:
202 returnValue = super.onOptionsItemSelected(item);
203 }
204
205 return returnValue;
206 }
207
208
209 @Override
210 protected void onResume() {
211 super.onResume();
212 //Log.e(TAG, "ACTIVITY, ONRESUME");
213 mDownloadFinishReceiver = new DownloadFinishReceiver();
214 IntentFilter filter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
215 filter.addAction(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
216 registerReceiver(mDownloadFinishReceiver, filter);
217 }
218
219 @Override
220 protected void onPostResume() {
221 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
222 super.onPostResume();
223 }
224
225 @Override
226 public void onPause() {
227 super.onPause();
228 unregisterReceiver(mDownloadFinishReceiver);
229 mDownloadFinishReceiver = null;
230 }
231
232
233 private void backToDisplayActivity() {
234 finish();
235 }
236
237
238 @Override
239 protected Dialog onCreateDialog(int id) {
240 Dialog dialog = null;
241 switch (id) {
242 case DIALOG_SHORT_WAIT: {
243 ProgressDialog working_dialog = new ProgressDialog(this);
244 working_dialog.setMessage(getResources().getString(
245 R.string.wait_a_moment));
246 working_dialog.setIndeterminate(true);
247 working_dialog.setCancelable(false);
248 dialog = working_dialog;
249 break;
250 }
251 default:
252 dialog = null;
253 }
254 return dialog;
255 }
256
257
258 /**
259 * {@inheritDoc}
260 */
261 @Override
262 public void onFileStateChanged() {
263 // nothing to do here!
264 }
265
266
267 /**
268 * {@inheritDoc}
269 */
270 @Override
271 public FileDownloaderBinder getFileDownloaderBinder() {
272 return mDownloaderBinder;
273 }
274
275
276 @Override
277 public FileUploaderBinder getFileUploaderBinder() {
278 return mUploaderBinder;
279 }
280
281
282 @Override
283 public void showDetails(OCFile file) {
284 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
285 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
286 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
287 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
288 startActivity(showDetailsIntent);
289 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
290 file = mPreviewImagePagerAdapter.getFileAt(pos);
291
292 }
293
294
295 private void requestForDownload(OCFile file) {
296 if (mDownloaderBinder == null) {
297 Log_OC.d(TAG, "requestForDownload called without binder to download service");
298
299 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
300 Intent i = new Intent(this, FileDownloader.class);
301 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
302 i.putExtra(FileDownloader.EXTRA_FILE, file);
303 startService(i);
304 }
305 }
306
307 /**
308 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
309 *
310 * @param Position Position index of the new selected page
311 */
312 @Override
313 public void onPageSelected(int position) {
314 if (mDownloaderBinder == null) {
315 mRequestWaitingForBinder = true;
316
317 } else {
318 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
319 getSupportActionBar().setTitle(currentFile.getFileName());
320 if (!currentFile.isDown()) {
321 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
322 requestForDownload(currentFile);
323 }
324 }
325 }
326 }
327
328 /**
329 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
330 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
331 *
332 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
333 */
334 @Override
335 public void onPageScrollStateChanged(int state) {
336 }
337
338 /**
339 * This method will be invoked when the current page is scrolled, either as part of a programmatically
340 * initiated smooth scroll or a user initiated touch scroll.
341 *
342 * @param position Position index of the first page currently being displayed.
343 * Page position+1 will be visible if positionOffset is nonzero.
344 *
345 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
346 * @param positionOffsetPixels Value in pixels indicating the offset from position.
347 */
348 @Override
349 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
350 }
351
352
353 /**
354 * Class waiting for broadcast events from the {@link FielDownloader} service.
355 *
356 * Updates the UI when a download is started or finished, provided that it is relevant for the
357 * folder displayed in the gallery.
358 */
359 private class DownloadFinishReceiver extends BroadcastReceiver {
360 @Override
361 public void onReceive(Context context, Intent intent) {
362 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
363 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
364 if (getAccount().name.equals(accountName) &&
365 downloadedRemotePath != null) {
366
367 OCFile file = mStorageManager.getFileByPath(downloadedRemotePath);
368 int position = mPreviewImagePagerAdapter.getFilePosition(file);
369 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
370 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
371
372 if (position >= 0 && intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
373 if (downloadWasFine) {
374 mPreviewImagePagerAdapter.updateFile(position, file);
375
376 } else {
377 mPreviewImagePagerAdapter.updateWithDownloadError(position);
378 }
379 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
380
381 } else {
382 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
383 }
384
385 }
386 removeStickyBroadcast(intent);
387 }
388
389 }
390
391
392 @Override
393 public boolean onTouch(View v, MotionEvent event) {
394 if (event.getAction() == MotionEvent.ACTION_UP) {
395 toggleFullScreen();
396 }
397 return true;
398 }
399
400
401 private void toggleFullScreen() {
402 ActionBar actionBar = getSupportActionBar();
403 if (mFullScreen) {
404 actionBar.show();
405
406 } else {
407 actionBar.hide();
408
409 }
410 mFullScreen = !mFullScreen;
411 }
412
413 @Override
414 protected void onAccountSet(boolean stateWasRecovered) {
415 if (getAccount() != null) {
416 OCFile file = getFile();
417 /// Validate handled file (first image to preview)
418 if (file == null) {
419 throw new IllegalStateException("Instanced with a NULL OCFile");
420 }
421 if (!file.isImage()) {
422 throw new IllegalArgumentException("Non-image file passed as argument");
423 }
424 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
425 file = mStorageManager.getFileById(file.getFileId());
426 if (file != null) {
427 /// Refresh the activity according to the Account and OCFile set
428 setFile(file); // reset after getting it fresh from mStorageManager
429 getSupportActionBar().setTitle(getFile().getFileName());
430 //if (!stateWasRecovered) {
431 initViewPager();
432 //}
433
434 } else {
435 // handled file not in the current Account
436 finish();
437 }
438
439 } else {
440 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
441 }
442 }
443
444
445 }