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
;
61 import org
.apache
.http
.HttpEntity
;
62 import org
.apache
.http
.HttpResponse
;
63 import org
.apache
.http
.auth
.AuthScope
;
64 import org
.apache
.http
.auth
.UsernamePasswordCredentials
;
65 import org
.apache
.http
.client
.methods
.HttpGet
;
66 import org
.apache
.http
.impl
.client
.DefaultHttpClient
;
67 import org
.apache
.http
.util
.EntityUtils
;
71 * This Adapter populates a ListView with all files and folders in an ownCloud
74 * @author Bartek Przybylski
75 * @Author Tobias Kaminsky
78 public class FileListListAdapter
extends BaseAdapter
implements ListAdapter
{
79 private final static String PERMISSION_SHARED_WITH_ME
= "S";
81 private Context mContext
;
82 private OCFile mFile
= null
;
83 private Vector
<OCFile
> mFiles
= null
;
85 private FileDataStorageManager mStorageManager
;
86 private Account mAccount
;
87 private ComponentsGetter mTransferServiceGetter
;
88 private final Object thumbnailDiskCacheLock
= new Object();
89 private DiskLruImageCache mThumbnailCache
;
90 private boolean mThumbnailCacheStarting
= true
;
91 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
92 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
93 private static final int mCompressQuality
= 70;
94 private OwnCloudClient mClient
;
95 private Bitmap defaultImg
;
97 public FileListListAdapter(Context context
, ComponentsGetter transferServiceGetter
) {
99 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
100 mTransferServiceGetter
= transferServiceGetter
;
101 defaultImg
= BitmapFactory
.decodeResource(mContext
.getResources(),
102 DisplayUtils
.getResourceId("image/png", "default.png"));
104 // Initialise disk cache on background thread
105 new InitDiskCacheTask().execute();
108 class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
110 protected Void
doInBackground(File
... params
) {
111 synchronized (thumbnailDiskCacheLock
) {
112 mThumbnailCache
= new DiskLruImageCache(mContext
, "thumbnailCache",
113 DISK_CACHE_SIZE
, mCompressFormat
, mCompressQuality
);
116 OwnCloudAccount ocAccount
= new OwnCloudAccount(mAccount
, mContext
);
117 mClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
118 getClientFor(ocAccount
, mContext
);
119 } catch (AccountNotFoundException e
) {
120 // TODO Auto-generated catch block
122 } catch (AuthenticatorException e
) {
123 // TODO Auto-generated catch block
125 } catch (OperationCanceledException e
) {
126 // TODO Auto-generated catch block
128 } catch (IOException e
) {
129 // TODO Auto-generated catch block
133 mThumbnailCacheStarting
= false
; // Finished initialization
134 thumbnailDiskCacheLock
.notifyAll(); // Wake any waiting threads
140 static class AsyncDrawable
extends BitmapDrawable
{
141 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
143 public AsyncDrawable(Resources res
, Bitmap bitmap
,
144 ThumbnailGenerationTask bitmapWorkerTask
) {
146 bitmapWorkerTaskReference
=
147 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
150 public ThumbnailGenerationTask
getBitmapWorkerTask() {
151 return bitmapWorkerTaskReference
.get();
155 class ThumbnailGenerationTask
extends AsyncTask
<OCFile
, Void
, Bitmap
> {
156 private final WeakReference
<ImageView
> imageViewReference
;
160 public ThumbnailGenerationTask(ImageView imageView
) {
161 // Use a WeakReference to ensure the ImageView can be garbage collected
162 imageViewReference
= new WeakReference
<ImageView
>(imageView
);
165 // Decode image in background.
167 protected Bitmap
doInBackground(OCFile
... params
) {
169 final String imageKey
= String
.valueOf(file
.getRemoteId());
171 // Check disk cache in background thread
172 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
174 // Not found in disk cache
175 if (thumbnail
== null
) {
176 // Converts dp to pixel
177 Resources r
= mContext
.getResources();
178 int px
= (int) Math
.round(TypedValue
.applyDimension(TypedValue
.COMPLEX_UNIT_DIP
, 150, r
.getDisplayMetrics()));
181 Bitmap bitmap
= BitmapFactory
.decodeFile(file
.getStoragePath());
182 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
184 // Add thumbnail to cache
185 addBitmapToCache(imageKey
, thumbnail
);
188 // Download thumbnail from server
189 // Commented out as maybe changes to client library are needed
190 DefaultHttpClient httpclient
= new DefaultHttpClient();
192 httpclient
.getCredentialsProvider().setCredentials(
193 new AuthScope(mClient
.getBaseUri().toString().replace("https://", ""), 443),
194 new UsernamePasswordCredentials(mClient
.getCredentials().getUsername(), mClient
.getCredentials().getAuthToken()));
197 HttpGet httpget
= new HttpGet(mClient
.getBaseUri() + "/ocs/v1.php/thumbnail?x=50&y=50&path=" + URLEncoder
.encode(file
.getRemotePath(), "UTF-8"));
198 HttpResponse response
= httpclient
.execute(httpget
);
199 HttpEntity entity
= response
.getEntity();
201 if (entity
!= null
) {
202 byte[] bytes
= EntityUtils
.toByteArray(entity
);
203 Bitmap bitmap
= BitmapFactory
.decodeByteArray(bytes
, 0, bytes
.length
);
204 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
206 // Add thumbnail to cache
207 if (thumbnail
!= null
){
208 addBitmapToCache(imageKey
, thumbnail
);
211 } catch(Exception e
){
214 httpclient
.getConnectionManager().shutdown();
221 protected void onPostExecute(Bitmap bitmap
){
226 if (imageViewReference
!= null
&& bitmap
!= null
) {
227 final ImageView imageView
= imageViewReference
.get();
228 final ThumbnailGenerationTask bitmapWorkerTask
=
229 getBitmapWorkerTask(imageView
);
230 if (this == bitmapWorkerTask
&& imageView
!= null
) {
231 imageView
.setImageBitmap(bitmap
);
237 public void addBitmapToCache(String key
, Bitmap bitmap
) {
238 synchronized (thumbnailDiskCacheLock
) {
239 if (mThumbnailCache
!= null
&& mThumbnailCache
.getBitmap(key
) == null
) {
240 mThumbnailCache
.put(key
, bitmap
);
245 public Bitmap
getBitmapFromDiskCache(String key
) {
246 synchronized (thumbnailDiskCacheLock
) {
247 // Wait while disk cache is started from background thread
248 while (mThumbnailCacheStarting
) {
250 thumbnailDiskCacheLock
.wait();
251 } catch (InterruptedException e
) {}
253 if (mThumbnailCache
!= null
) {
254 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
261 public boolean areAllItemsEnabled() {
266 public boolean isEnabled(int position
) {
271 public int getCount() {
272 return mFiles
!= null ? mFiles
.size() : 0;
276 public Object
getItem(int position
) {
277 if (mFiles
== null
|| mFiles
.size() <= position
)
279 return mFiles
.get(position
);
283 public long getItemId(int position
) {
284 if (mFiles
== null
|| mFiles
.size() <= position
)
286 return mFiles
.get(position
).getFileId();
290 public int getItemViewType(int position
) {
295 public View
getView(int position
, View convertView
, ViewGroup parent
) {
296 View view
= convertView
;
298 LayoutInflater inflator
= (LayoutInflater
) mContext
299 .getSystemService(Context
.LAYOUT_INFLATER_SERVICE
);
300 view
= inflator
.inflate(R
.layout
.list_item
, null
);
303 if (mFiles
!= null
&& mFiles
.size() > position
) {
304 OCFile file
= mFiles
.get(position
);
305 TextView fileName
= (TextView
) view
.findViewById(R
.id
.Filename
);
306 String name
= file
.getFileName();
308 fileName
.setText(name
);
309 ImageView fileIcon
= (ImageView
) view
.findViewById(R
.id
.imageView1
);
310 ImageView sharedIconV
= (ImageView
) view
.findViewById(R
.id
.sharedIcon
);
311 ImageView sharedWithMeIconV
= (ImageView
) view
.findViewById(R
.id
.sharedWithMeIcon
);
312 sharedWithMeIconV
.setVisibility(View
.GONE
);
314 ImageView localStateView
= (ImageView
) view
.findViewById(R
.id
.imageView2
);
315 localStateView
.bringToFront();
316 FileDownloaderBinder downloaderBinder
= mTransferServiceGetter
.getFileDownloaderBinder();
317 FileUploaderBinder uploaderBinder
= mTransferServiceGetter
.getFileUploaderBinder();
318 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, file
)) {
319 localStateView
.setImageResource(R
.drawable
.downloading_file_indicator
);
320 localStateView
.setVisibility(View
.VISIBLE
);
321 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, file
)) {
322 localStateView
.setImageResource(R
.drawable
.uploading_file_indicator
);
323 localStateView
.setVisibility(View
.VISIBLE
);
324 } else if (file
.isDown()) {
325 localStateView
.setImageResource(R
.drawable
.local_file_indicator
);
326 localStateView
.setVisibility(View
.VISIBLE
);
328 localStateView
.setVisibility(View
.INVISIBLE
);
331 TextView fileSizeV
= (TextView
) view
.findViewById(R
.id
.file_size
);
332 TextView lastModV
= (TextView
) view
.findViewById(R
.id
.last_mod
);
333 ImageView checkBoxV
= (ImageView
) view
.findViewById(R
.id
.custom_checkbox
);
335 if (!file
.isFolder()) {
336 fileSizeV
.setVisibility(View
.VISIBLE
);
337 fileSizeV
.setText(DisplayUtils
.bytesToHumanReadable(file
.getFileLength()));
338 lastModV
.setVisibility(View
.VISIBLE
);
339 lastModV
.setText(DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp()));
340 // this if-else is needed even thoe fav icon is visible by default
341 // because android reuses views in listview
342 if (!file
.keepInSync()) {
343 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
345 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.VISIBLE
);
348 ListView parentList
= (ListView
)parent
;
349 if (parentList
.getChoiceMode() == ListView
.CHOICE_MODE_NONE
) {
350 checkBoxV
.setVisibility(View
.GONE
);
352 if (parentList
.isItemChecked(position
)) {
353 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_on_background
);
355 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_off_background
);
357 checkBoxV
.setVisibility(View
.VISIBLE
);
360 // get Thumbnail if file is image
362 // Thumbnail in Cache?
363 Bitmap thumbnail
= getBitmapFromDiskCache(String
.valueOf(file
.getRemoteId()));
364 if (thumbnail
!= null
){
365 fileIcon
.setImageBitmap(thumbnail
);
367 // generate new Thumbnail
368 if (cancelPotentialWork(file
, fileIcon
)) {
369 final ThumbnailGenerationTask task
= new ThumbnailGenerationTask(fileIcon
);
370 final AsyncDrawable asyncDrawable
=
371 new AsyncDrawable(mContext
.getResources(), defaultImg
, task
);
372 fileIcon
.setImageDrawable(asyncDrawable
);
377 fileIcon
.setImageResource(DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName()));
380 if (checkIfFileIsSharedWithMe(file
)) {
381 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
385 fileSizeV
.setVisibility(View
.INVISIBLE
);
386 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
387 lastModV
.setVisibility(View
.VISIBLE
);
388 lastModV
.setText(DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp()));
389 checkBoxV
.setVisibility(View
.GONE
);
390 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
392 if (checkIfFileIsSharedWithMe(file
)) {
393 fileIcon
.setImageResource(R
.drawable
.shared_with_me_folder
);
394 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
396 fileIcon
.setImageResource(DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName()));
399 // If folder is sharedByLink, icon folder must be changed to
401 if (file
.isShareByLink()) {
402 fileIcon
.setImageResource(R
.drawable
.folder_public
);
406 if (file
.isShareByLink()) {
407 sharedIconV
.setVisibility(View
.VISIBLE
);
409 sharedIconV
.setVisibility(View
.GONE
);
416 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
417 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
419 if (bitmapWorkerTask
!= null
) {
420 final OCFile bitmapData
= bitmapWorkerTask
.file
;
421 // If bitmapData is not yet set or it differs from the new data
422 if (bitmapData
== null
|| bitmapData
!= file
) {
423 // Cancel previous task
424 bitmapWorkerTask
.cancel(true
);
426 // The same work is already in progress
430 // No task associated with the ImageView, or an existing task was cancelled
434 private static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
435 if (imageView
!= null
) {
436 final Drawable drawable
= imageView
.getDrawable();
437 if (drawable
instanceof AsyncDrawable
) {
438 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
439 return asyncDrawable
.getBitmapWorkerTask();
446 public int getViewTypeCount() {
451 public boolean hasStableIds() {
456 public boolean isEmpty() {
457 return (mFiles
== null
|| mFiles
.isEmpty());
461 * Change the adapted directory for a new one
462 * @param directory New file to adapt. Can be NULL, meaning "no content to adapt".
463 * @param updatedStorageManager Optional updated storage manager; used to replace mStorageManager if is different (and not NULL)
465 public void swapDirectory(OCFile directory
, FileDataStorageManager updatedStorageManager
) {
467 if (updatedStorageManager
!= null
&& updatedStorageManager
!= mStorageManager
) {
468 mStorageManager
= updatedStorageManager
;
469 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
471 if (mStorageManager
!= null
) {
472 mFiles
= mStorageManager
.getFolderContent(mFile
);
476 notifyDataSetChanged();
480 * Check if parent folder does not include 'S' permission and if file/folder
483 * @param file: OCFile
484 * @return boolean: True if it is shared with me and false if it is not
486 private boolean checkIfFileIsSharedWithMe(OCFile file
) {
487 return (mFile
.getPermissions() != null
&& !mFile
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
)
488 && file
.getPermissions() != null
&& file
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
));