1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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.
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/>.
18 package com
.owncloud
.android
.ui
.adapter
;
21 import java
.io
.IOException
;
22 import java
.lang
.ref
.WeakReference
;
23 //import java.net.URLEncoder;
24 import java
.util
.Vector
;
26 import android
.accounts
.Account
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.accounts
.OperationCanceledException
;
29 import android
.content
.Context
;
30 import android
.content
.res
.Resources
;
31 import android
.graphics
.Bitmap
;
32 import android
.graphics
.Bitmap
.CompressFormat
;
33 import android
.graphics
.BitmapFactory
;
34 import android
.graphics
.drawable
.BitmapDrawable
;
35 import android
.graphics
.drawable
.Drawable
;
36 import android
.media
.ThumbnailUtils
;
37 import android
.os
.AsyncTask
;
38 import android
.util
.TypedValue
;
39 import android
.view
.LayoutInflater
;
40 import android
.view
.View
;
41 import android
.view
.ViewGroup
;
42 import android
.widget
.BaseAdapter
;
43 import android
.widget
.ImageView
;
44 import android
.widget
.ListAdapter
;
45 import android
.widget
.ListView
;
46 import android
.widget
.TextView
;
48 import com
.owncloud
.android
.R
;
49 import com
.owncloud
.android
.authentication
.AccountUtils
;
50 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
51 import com
.owncloud
.android
.datamodel
.OCFile
;
52 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
53 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
54 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
55 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
56 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
57 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
58 import com
.owncloud
.android
.ui
.activity
.ComponentsGetter
;
59 import com
.owncloud
.android
.utils
.DisplayUtils
;
62 import org.apache.http.HttpEntity;
63 import org.apache.http.HttpResponse;
64 import org.apache.http.auth.AuthScope;
65 import org.apache.http.auth.UsernamePasswordCredentials;
66 import org.apache.http.client.methods.HttpGet;
67 import org.apache.http.impl.client.DefaultHttpClient;
68 import org.apache.http.util.EntityUtils;
73 * This Adapter populates a ListView with all files and folders in an ownCloud
76 * @author Bartek Przybylski
77 * @Author Tobias Kaminsky
80 public class FileListListAdapter
extends BaseAdapter
implements ListAdapter
{
81 private final static String PERMISSION_SHARED_WITH_ME
= "S";
83 private Context mContext
;
84 private OCFile mFile
= null
;
85 private Vector
<OCFile
> mFiles
= null
;
86 private boolean mJustFolders
;
88 private FileDataStorageManager mStorageManager
;
89 private Account mAccount
;
90 private ComponentsGetter mTransferServiceGetter
;
92 private final Object thumbnailDiskCacheLock
= new Object();
93 private DiskLruImageCache mThumbnailCache
;
94 private boolean mThumbnailCacheStarting
= true
;
95 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
96 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
97 private static final int mCompressQuality
= 70;
98 private Bitmap defaultImg
;
100 public FileListListAdapter(
103 ComponentsGetter transferServiceGetter
106 mJustFolders
= justFolders
;
108 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
109 mTransferServiceGetter
= transferServiceGetter
;
110 defaultImg
= BitmapFactory
.decodeResource(mContext
.getResources(),
111 DisplayUtils
.getResourceId("image/png", "default.png"));
113 // Initialise disk cache on background thread
114 new InitDiskCacheTask().execute();
117 class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
119 protected Void
doInBackground(File
... params
) {
120 synchronized (thumbnailDiskCacheLock
) {
121 mThumbnailCache
= new DiskLruImageCache(mContext
, "thumbnailCache",
122 DISK_CACHE_SIZE
, mCompressFormat
, mCompressQuality
);
124 mThumbnailCacheStarting
= false
; // Finished initialization
125 thumbnailDiskCacheLock
.notifyAll(); // Wake any waiting threads
131 static class AsyncDrawable
extends BitmapDrawable
{
132 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
134 public AsyncDrawable(Resources res
, Bitmap bitmap
,
135 ThumbnailGenerationTask bitmapWorkerTask
) {
137 bitmapWorkerTaskReference
=
138 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
141 public ThumbnailGenerationTask
getBitmapWorkerTask() {
142 return bitmapWorkerTaskReference
.get();
146 class ThumbnailGenerationTask
extends AsyncTask
<OCFile
, Void
, Bitmap
> {
147 private final WeakReference
<ImageView
> imageViewReference
;
151 public ThumbnailGenerationTask(ImageView imageView
) {
152 // Use a WeakReference to ensure the ImageView can be garbage collected
153 imageViewReference
= new WeakReference
<ImageView
>(imageView
);
156 // Decode image in background.
158 protected Bitmap
doInBackground(OCFile
... params
) {
160 final String imageKey
= String
.valueOf(file
.getRemoteId());
162 // Check disk cache in background thread
163 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
165 // Not found in disk cache
166 if (thumbnail
== null
) {
167 // Converts dp to pixel
168 Resources r
= mContext
.getResources();
169 int px
= (int) Math
.round(TypedValue
.applyDimension(
170 TypedValue
.COMPLEX_UNIT_DIP
, 150, r
.getDisplayMetrics()
174 Bitmap bitmap
= BitmapFactory
.decodeFile(file
.getStoragePath());
176 if (bitmap
!= null
) {
177 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
179 // Add thumbnail to cache
180 addBitmapToCache(imageKey
, thumbnail
);
184 // Download thumbnail from server
185 // Commented out as maybe changes to client library are needed
186 // DefaultHttpClient httpclient = new DefaultHttpClient();
188 // httpclient.getCredentialsProvider().setCredentials(
189 // new AuthScope(mClient.getBaseUri().toString().replace("https://", ""), 443),
190 // new UsernamePasswordCredentials(mClient.getCredentials().getUsername(), mClient.getCredentials().getAuthToken()));
193 // HttpGet httpget = new HttpGet(mClient.getBaseUri() + "/ocs/v1.php/thumbnail?x=50&y=50&path=" + URLEncoder.encode(file.getRemotePath(), "UTF-8"));
194 // HttpResponse response = httpclient.execute(httpget);
195 // HttpEntity entity = response.getEntity();
197 // if (entity != null) {
198 // byte[] bytes = EntityUtils.toByteArray(entity);
199 // Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
200 // thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
202 // // Add thumbnail to cache
203 // if (thumbnail != null){
204 // addBitmapToCache(imageKey, thumbnail);
207 // } catch(Exception e){
208 // e.printStackTrace();
210 // httpclient.getConnectionManager().shutdown();
217 protected void onPostExecute(Bitmap bitmap
){
222 if (imageViewReference
!= null
&& bitmap
!= null
) {
223 final ImageView imageView
= imageViewReference
.get();
224 final ThumbnailGenerationTask bitmapWorkerTask
=
225 getBitmapWorkerTask(imageView
);
226 if (this == bitmapWorkerTask
&& imageView
!= null
) {
227 imageView
.setImageBitmap(bitmap
);
233 public void addBitmapToCache(String key
, Bitmap bitmap
) {
234 synchronized (thumbnailDiskCacheLock
) {
235 if (mThumbnailCache
!= null
&& mThumbnailCache
.getBitmap(key
) == null
) {
236 mThumbnailCache
.put(key
, bitmap
);
241 public Bitmap
getBitmapFromDiskCache(String key
) {
242 synchronized (thumbnailDiskCacheLock
) {
243 // Wait while disk cache is started from background thread
244 while (mThumbnailCacheStarting
) {
246 thumbnailDiskCacheLock
.wait();
247 } catch (InterruptedException e
) {}
249 if (mThumbnailCache
!= null
) {
250 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
257 public boolean areAllItemsEnabled() {
262 public boolean isEnabled(int position
) {
267 public int getCount() {
268 return mFiles
!= null ? mFiles
.size() : 0;
272 public Object
getItem(int position
) {
273 if (mFiles
== null
|| mFiles
.size() <= position
)
275 return mFiles
.get(position
);
279 public long getItemId(int position
) {
280 if (mFiles
== null
|| mFiles
.size() <= position
)
282 return mFiles
.get(position
).getFileId();
286 public int getItemViewType(int position
) {
291 public View
getView(int position
, View convertView
, ViewGroup parent
) {
292 View view
= convertView
;
294 LayoutInflater inflator
= (LayoutInflater
) mContext
295 .getSystemService(Context
.LAYOUT_INFLATER_SERVICE
);
296 view
= inflator
.inflate(R
.layout
.list_item
, null
);
299 if (mFiles
!= null
&& mFiles
.size() > position
) {
300 OCFile file
= mFiles
.get(position
);
301 TextView fileName
= (TextView
) view
.findViewById(R
.id
.Filename
);
302 String name
= file
.getFileName();
304 fileName
.setText(name
);
305 ImageView fileIcon
= (ImageView
) view
.findViewById(R
.id
.imageView1
);
306 ImageView sharedIconV
= (ImageView
) view
.findViewById(R
.id
.sharedIcon
);
307 ImageView sharedWithMeIconV
= (ImageView
) view
.findViewById(R
.id
.sharedWithMeIcon
);
308 sharedWithMeIconV
.setVisibility(View
.GONE
);
310 ImageView localStateView
= (ImageView
) view
.findViewById(R
.id
.imageView2
);
311 localStateView
.bringToFront();
312 FileDownloaderBinder downloaderBinder
=
313 mTransferServiceGetter
.getFileDownloaderBinder();
314 FileUploaderBinder uploaderBinder
= mTransferServiceGetter
.getFileUploaderBinder();
315 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, file
)) {
316 localStateView
.setImageResource(R
.drawable
.downloading_file_indicator
);
317 localStateView
.setVisibility(View
.VISIBLE
);
318 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, file
)) {
319 localStateView
.setImageResource(R
.drawable
.uploading_file_indicator
);
320 localStateView
.setVisibility(View
.VISIBLE
);
321 } else if (file
.isDown()) {
322 localStateView
.setImageResource(R
.drawable
.local_file_indicator
);
323 localStateView
.setVisibility(View
.VISIBLE
);
325 localStateView
.setVisibility(View
.INVISIBLE
);
328 TextView fileSizeV
= (TextView
) view
.findViewById(R
.id
.file_size
);
329 TextView lastModV
= (TextView
) view
.findViewById(R
.id
.last_mod
);
330 ImageView checkBoxV
= (ImageView
) view
.findViewById(R
.id
.custom_checkbox
);
332 if (!file
.isFolder()) {
333 fileSizeV
.setVisibility(View
.VISIBLE
);
334 fileSizeV
.setText(DisplayUtils
.bytesToHumanReadable(file
.getFileLength()));
335 lastModV
.setVisibility(View
.VISIBLE
);
337 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
339 // this if-else is needed even thoe fav icon is visible by default
340 // because android reuses views in listview
341 if (!file
.keepInSync()) {
342 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
344 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.VISIBLE
);
347 ListView parentList
= (ListView
)parent
;
348 if (parentList
.getChoiceMode() == ListView
.CHOICE_MODE_NONE
) {
349 checkBoxV
.setVisibility(View
.GONE
);
351 if (parentList
.isItemChecked(position
)) {
352 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_on_background
);
354 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_off_background
);
356 checkBoxV
.setVisibility(View
.VISIBLE
);
359 // get Thumbnail if file is image
361 // Thumbnail in Cache?
362 Bitmap thumbnail
= getBitmapFromDiskCache(String
.valueOf(file
.getRemoteId()));
363 if (thumbnail
!= null
){
364 fileIcon
.setImageBitmap(thumbnail
);
366 // generate new Thumbnail
367 if (cancelPotentialWork(file
, fileIcon
)) {
368 final ThumbnailGenerationTask task
=
369 new ThumbnailGenerationTask(fileIcon
);
370 final AsyncDrawable asyncDrawable
=
371 new AsyncDrawable(mContext
.getResources(), defaultImg
, task
);
372 fileIcon
.setImageDrawable(asyncDrawable
);
377 fileIcon
.setImageResource(
378 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
382 if (checkIfFileIsSharedWithMe(file
)) {
383 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
387 fileSizeV
.setVisibility(View
.INVISIBLE
);
388 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
389 lastModV
.setVisibility(View
.VISIBLE
);
391 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
393 checkBoxV
.setVisibility(View
.GONE
);
394 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
396 if (checkIfFileIsSharedWithMe(file
)) {
397 fileIcon
.setImageResource(R
.drawable
.shared_with_me_folder
);
398 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
400 fileIcon
.setImageResource(
401 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
405 // If folder is sharedByLink, icon folder must be changed to
407 if (file
.isShareByLink()) {
408 fileIcon
.setImageResource(R
.drawable
.folder_public
);
412 if (file
.isShareByLink()) {
413 sharedIconV
.setVisibility(View
.VISIBLE
);
415 sharedIconV
.setVisibility(View
.GONE
);
422 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
423 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
425 if (bitmapWorkerTask
!= null
) {
426 final OCFile bitmapData
= bitmapWorkerTask
.file
;
427 // If bitmapData is not yet set or it differs from the new data
428 if (bitmapData
== null
|| bitmapData
!= file
) {
429 // Cancel previous task
430 bitmapWorkerTask
.cancel(true
);
432 // The same work is already in progress
436 // No task associated with the ImageView, or an existing task was cancelled
440 private static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
441 if (imageView
!= null
) {
442 final Drawable drawable
= imageView
.getDrawable();
443 if (drawable
instanceof AsyncDrawable
) {
444 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
445 return asyncDrawable
.getBitmapWorkerTask();
452 public int getViewTypeCount() {
457 public boolean hasStableIds() {
462 public boolean isEmpty() {
463 return (mFiles
== null
|| mFiles
.isEmpty());
467 * Change the adapted directory for a new one
468 * @param directory New file to adapt. Can be NULL, meaning
469 * "no content to adapt".
470 * @param updatedStorageManager Optional updated storage manager; used to replace
471 * mStorageManager if is different (and not NULL)
473 public void swapDirectory(OCFile directory
, FileDataStorageManager updatedStorageManager
) {
475 if (updatedStorageManager
!= null
&& updatedStorageManager
!= mStorageManager
) {
476 mStorageManager
= updatedStorageManager
;
477 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
479 if (mStorageManager
!= null
) {
480 mFiles
= mStorageManager
.getFolderContent(mFile
);
482 mFiles
= getFolders(mFiles
);
487 notifyDataSetChanged();
492 * Filter for getting only the folders
494 * @return Vector<OCFile>
496 public Vector
<OCFile
> getFolders(Vector
<OCFile
> files
) {
497 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
498 OCFile current
= null
;
499 for (int i
=0; i
<files
.size(); i
++) {
500 current
= files
.get(i
);
501 if (current
.isFolder()) {
510 * Check if parent folder does not include 'S' permission and if file/folder
513 * @param file: OCFile
514 * @return boolean: True if it is shared with me and false if it is not
516 private boolean checkIfFileIsSharedWithMe(OCFile file
) {
517 return (mFile
.getPermissions() != null
518 && !mFile
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
)
519 && file
.getPermissions() != null
520 && file
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
));