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
;
20 import java
.io
.ByteArrayInputStream
;
22 import java
.io
.IOException
;
23 import java
.io
.InputStream
;
24 import java
.lang
.ref
.WeakReference
;
25 import java
.net
.URLEncoder
;
26 //import java.net.URLEncoder;
27 import java
.util
.Vector
;
29 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
30 import org
.apache
.http
.HttpStatus
;
32 import android
.accounts
.Account
;
33 import android
.accounts
.AuthenticatorException
;
34 import android
.accounts
.OperationCanceledException
;
35 import android
.content
.Context
;
36 import android
.content
.res
.Resources
;
37 import android
.graphics
.Bitmap
;
38 import android
.graphics
.Bitmap
.CompressFormat
;
39 import android
.graphics
.BitmapFactory
;
40 import android
.graphics
.drawable
.BitmapDrawable
;
41 import android
.graphics
.drawable
.Drawable
;
42 import android
.media
.ThumbnailUtils
;
43 import android
.os
.AsyncTask
;
44 import android
.util
.TypedValue
;
45 import android
.view
.LayoutInflater
;
46 import android
.view
.View
;
47 import android
.view
.ViewGroup
;
48 import android
.widget
.BaseAdapter
;
49 import android
.widget
.ImageView
;
50 import android
.widget
.ListAdapter
;
51 import android
.widget
.ListView
;
52 import android
.widget
.TextView
;
54 import com
.owncloud
.android
.R
;
55 import com
.owncloud
.android
.authentication
.AccountUtils
;
56 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
57 import com
.owncloud
.android
.datamodel
.OCFile
;
58 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
59 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
60 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
61 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
62 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
63 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
64 import com
.owncloud
.android
.lib
.resources
.shares
.ShareUtils
;
65 import com
.owncloud
.android
.ui
.activity
.ComponentsGetter
;
66 import com
.owncloud
.android
.utils
.DisplayUtils
;
67 import com
.owncloud
.android
.utils
.Log_OC
;
70 import org.apache.http.HttpEntity;
71 import org.apache.http.HttpResponse;
72 import org.apache.http.auth.AuthScope;
73 import org.apache.http.auth.UsernamePasswordCredentials;
74 import org.apache.http.client.methods.HttpGet;
75 import org.apache.http.impl.client.DefaultHttpClient;
76 import org.apache.http.util.EntityUtils;
81 * This Adapter populates a ListView with all files and folders in an ownCloud
84 * @author Bartek Przybylski
85 * @Author Tobias Kaminsky
88 public class FileListListAdapter
extends BaseAdapter
implements ListAdapter
{
89 private final static String PERMISSION_SHARED_WITH_ME
= "S";
91 private Context mContext
;
92 private OCFile mFile
= null
;
93 private Vector
<OCFile
> mFiles
= null
;
94 private boolean mJustFolders
;
96 private FileDataStorageManager mStorageManager
;
97 private Account mAccount
;
98 private ComponentsGetter mTransferServiceGetter
;
100 private final Object thumbnailDiskCacheLock
= new Object();
101 private DiskLruImageCache mThumbnailCache
;
102 private boolean mThumbnailCacheStarting
= true
;
103 private static final int DISK_CACHE_SIZE
= 1024 * 1024 * 10; // 10MB
104 private static final CompressFormat mCompressFormat
= CompressFormat
.JPEG
;
105 private static final int mCompressQuality
= 70;
106 private Bitmap defaultImg
;
107 private OwnCloudClient client
;
109 public FileListListAdapter(
112 ComponentsGetter transferServiceGetter
115 mJustFolders
= justFolders
;
117 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
118 mTransferServiceGetter
= transferServiceGetter
;
119 defaultImg
= BitmapFactory
.decodeResource(mContext
.getResources(),
120 DisplayUtils
.getResourceId("image/png", "default.png"));
122 // Initialise disk cache on background thread
123 new InitDiskCacheTask().execute();
129 class InitDiskCacheTask
extends AsyncTask
<File
, Void
, Void
> {
131 protected Void
doInBackground(File
... params
) {
132 synchronized (thumbnailDiskCacheLock
) {
133 OwnCloudAccount ocAccount
;
135 ocAccount
= new OwnCloudAccount(mAccount
, mContext
);
136 client
= OwnCloudClientManagerFactory
.getDefaultSingleton().
137 getClientFor(ocAccount
, mContext
);
138 } catch (AccountNotFoundException e
) {
139 // TODO Auto-generated catch block
141 } catch (AuthenticatorException e
) {
142 // TODO Auto-generated catch block
144 } catch (OperationCanceledException e
) {
145 // TODO Auto-generated catch block
147 } catch (IOException e
) {
148 // TODO Auto-generated catch block
153 mThumbnailCache
= new DiskLruImageCache(mContext
, "thumbnailCache",
154 DISK_CACHE_SIZE
, mCompressFormat
, mCompressQuality
);
156 mThumbnailCacheStarting
= false
; // Finished initialization
157 thumbnailDiskCacheLock
.notifyAll(); // Wake any waiting threads
163 static class AsyncDrawable
extends BitmapDrawable
{
164 private final WeakReference
<ThumbnailGenerationTask
> bitmapWorkerTaskReference
;
166 public AsyncDrawable(Resources res
, Bitmap bitmap
,
167 ThumbnailGenerationTask bitmapWorkerTask
) {
169 bitmapWorkerTaskReference
=
170 new WeakReference
<ThumbnailGenerationTask
>(bitmapWorkerTask
);
173 public ThumbnailGenerationTask
getBitmapWorkerTask() {
174 return bitmapWorkerTaskReference
.get();
178 class ThumbnailGenerationTask
extends AsyncTask
<OCFile
, Void
, Bitmap
> {
179 private final WeakReference
<ImageView
> imageViewReference
;
183 public ThumbnailGenerationTask(ImageView imageView
) {
184 // Use a WeakReference to ensure the ImageView can be garbage collected
185 imageViewReference
= new WeakReference
<ImageView
>(imageView
);
188 // Decode image in background.
190 protected Bitmap
doInBackground(OCFile
... params
) {
192 final String imageKey
= String
.valueOf(file
.getRemoteId().hashCode());
193 Log_OC
.d("Thumbnail", imageKey
);
195 // Check disk cache in background thread
196 Bitmap thumbnail
= getBitmapFromDiskCache(imageKey
);
198 // Not found in disk cache
199 if (thumbnail
== null
) {
200 // Converts dp to pixel
201 Resources r
= mContext
.getResources();
202 int px
= (int) Math
.round(TypedValue
.applyDimension(
203 TypedValue
.COMPLEX_UNIT_DIP
, 150, r
.getDisplayMetrics()
207 Bitmap bitmap
= BitmapFactory
.decodeFile(file
.getStoragePath());
209 if (bitmap
!= null
) {
210 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
212 // Add thumbnail to cache
213 addBitmapToCache(imageKey
, thumbnail
);
217 // Download thumbnail from server
221 String uri
= client
.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/100/100/"+URLEncoder
.encode(file
.getRemotePath(), "UTF-8").replaceAll("%2F", "/");
222 Log_OC
.d("Thumbnail", "URI: " + uri
);
223 GetMethod get
= new GetMethod(uri
);
224 status
= client
.executeMethod(get
);
225 if(isSuccess(status
)) {
226 byte[] bytes
= get
.getResponseBody();
227 Bitmap bitmap
= BitmapFactory
.decodeByteArray(bytes
, 0, bytes
.length
);
228 thumbnail
= ThumbnailUtils
.extractThumbnail(bitmap
, px
, px
);
230 // Add thumbnail to cache
231 if (thumbnail
!= null
){
232 addBitmapToCache(imageKey
, thumbnail
);
235 } catch(Exception e
){
243 private boolean isSuccess(int status
) {
244 return (status
== HttpStatus
.SC_OK
);
248 protected void onPostExecute(Bitmap bitmap
){
253 if (imageViewReference
!= null
&& bitmap
!= null
) {
254 final ImageView imageView
= imageViewReference
.get();
255 final ThumbnailGenerationTask bitmapWorkerTask
=
256 getBitmapWorkerTask(imageView
);
257 if (this == bitmapWorkerTask
&& imageView
!= null
) {
258 imageView
.setImageBitmap(bitmap
);
264 public void addBitmapToCache(String key
, Bitmap bitmap
) {
265 synchronized (thumbnailDiskCacheLock
) {
266 if (mThumbnailCache
!= null
&& mThumbnailCache
.getBitmap(key
) == null
) {
267 mThumbnailCache
.put(key
, bitmap
);
272 public Bitmap
getBitmapFromDiskCache(String key
) {
273 synchronized (thumbnailDiskCacheLock
) {
274 // Wait while disk cache is started from background thread
275 while (mThumbnailCacheStarting
) {
277 thumbnailDiskCacheLock
.wait();
278 } catch (InterruptedException e
) {}
280 if (mThumbnailCache
!= null
) {
281 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
288 public boolean areAllItemsEnabled() {
293 public boolean isEnabled(int position
) {
298 public int getCount() {
299 return mFiles
!= null ? mFiles
.size() : 0;
303 public Object
getItem(int position
) {
304 if (mFiles
== null
|| mFiles
.size() <= position
)
306 return mFiles
.get(position
);
310 public long getItemId(int position
) {
311 if (mFiles
== null
|| mFiles
.size() <= position
)
313 return mFiles
.get(position
).getFileId();
317 public int getItemViewType(int position
) {
322 public View
getView(int position
, View convertView
, ViewGroup parent
) {
323 View view
= convertView
;
325 LayoutInflater inflator
= (LayoutInflater
) mContext
326 .getSystemService(Context
.LAYOUT_INFLATER_SERVICE
);
327 view
= inflator
.inflate(R
.layout
.list_item
, null
);
330 if (mFiles
!= null
&& mFiles
.size() > position
) {
331 OCFile file
= mFiles
.get(position
);
332 TextView fileName
= (TextView
) view
.findViewById(R
.id
.Filename
);
333 String name
= file
.getFileName();
335 fileName
.setText(name
);
336 ImageView fileIcon
= (ImageView
) view
.findViewById(R
.id
.imageView1
);
337 ImageView sharedIconV
= (ImageView
) view
.findViewById(R
.id
.sharedIcon
);
338 ImageView sharedWithMeIconV
= (ImageView
) view
.findViewById(R
.id
.sharedWithMeIcon
);
339 sharedWithMeIconV
.setVisibility(View
.GONE
);
341 ImageView localStateView
= (ImageView
) view
.findViewById(R
.id
.imageView2
);
342 localStateView
.bringToFront();
343 FileDownloaderBinder downloaderBinder
=
344 mTransferServiceGetter
.getFileDownloaderBinder();
345 FileUploaderBinder uploaderBinder
= mTransferServiceGetter
.getFileUploaderBinder();
346 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, file
)) {
347 localStateView
.setImageResource(R
.drawable
.downloading_file_indicator
);
348 localStateView
.setVisibility(View
.VISIBLE
);
349 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, file
)) {
350 localStateView
.setImageResource(R
.drawable
.uploading_file_indicator
);
351 localStateView
.setVisibility(View
.VISIBLE
);
352 } else if (file
.isDown()) {
353 localStateView
.setImageResource(R
.drawable
.local_file_indicator
);
354 localStateView
.setVisibility(View
.VISIBLE
);
356 localStateView
.setVisibility(View
.INVISIBLE
);
359 TextView fileSizeV
= (TextView
) view
.findViewById(R
.id
.file_size
);
360 TextView lastModV
= (TextView
) view
.findViewById(R
.id
.last_mod
);
361 ImageView checkBoxV
= (ImageView
) view
.findViewById(R
.id
.custom_checkbox
);
363 if (!file
.isFolder()) {
364 fileSizeV
.setVisibility(View
.VISIBLE
);
365 fileSizeV
.setText(DisplayUtils
.bytesToHumanReadable(file
.getFileLength()));
366 lastModV
.setVisibility(View
.VISIBLE
);
368 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
370 // this if-else is needed even thoe fav icon is visible by default
371 // because android reuses views in listview
372 if (!file
.keepInSync()) {
373 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
375 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.VISIBLE
);
378 ListView parentList
= (ListView
)parent
;
379 if (parentList
.getChoiceMode() == ListView
.CHOICE_MODE_NONE
) {
380 checkBoxV
.setVisibility(View
.GONE
);
382 if (parentList
.isItemChecked(position
)) {
383 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_on_background
);
385 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_off_background
);
387 checkBoxV
.setVisibility(View
.VISIBLE
);
390 // get Thumbnail if file is image
392 // Thumbnail in Cache?
393 Bitmap thumbnail
= getBitmapFromDiskCache(String
.valueOf(file
.getRemoteId().hashCode()));
394 if (thumbnail
!= null
){
395 fileIcon
.setImageBitmap(thumbnail
);
397 // generate new Thumbnail
398 if (cancelPotentialWork(file
, fileIcon
)) {
399 final ThumbnailGenerationTask task
=
400 new ThumbnailGenerationTask(fileIcon
);
401 final AsyncDrawable asyncDrawable
=
402 new AsyncDrawable(mContext
.getResources(), defaultImg
, task
);
403 fileIcon
.setImageDrawable(asyncDrawable
);
408 fileIcon
.setImageResource(
409 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
413 if (checkIfFileIsSharedWithMe(file
)) {
414 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
418 fileSizeV
.setVisibility(View
.INVISIBLE
);
419 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
420 lastModV
.setVisibility(View
.VISIBLE
);
422 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
424 checkBoxV
.setVisibility(View
.GONE
);
425 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
427 if (checkIfFileIsSharedWithMe(file
)) {
428 fileIcon
.setImageResource(R
.drawable
.shared_with_me_folder
);
429 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
431 fileIcon
.setImageResource(
432 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
436 // If folder is sharedByLink, icon folder must be changed to
438 if (file
.isShareByLink()) {
439 fileIcon
.setImageResource(R
.drawable
.folder_public
);
443 if (file
.isShareByLink()) {
444 sharedIconV
.setVisibility(View
.VISIBLE
);
446 sharedIconV
.setVisibility(View
.GONE
);
453 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
454 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
456 if (bitmapWorkerTask
!= null
) {
457 final OCFile bitmapData
= bitmapWorkerTask
.file
;
458 // If bitmapData is not yet set or it differs from the new data
459 if (bitmapData
== null
|| bitmapData
!= file
) {
460 // Cancel previous task
461 bitmapWorkerTask
.cancel(true
);
463 // The same work is already in progress
467 // No task associated with the ImageView, or an existing task was cancelled
471 private static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
472 if (imageView
!= null
) {
473 final Drawable drawable
= imageView
.getDrawable();
474 if (drawable
instanceof AsyncDrawable
) {
475 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
476 return asyncDrawable
.getBitmapWorkerTask();
483 public int getViewTypeCount() {
488 public boolean hasStableIds() {
493 public boolean isEmpty() {
494 return (mFiles
== null
|| mFiles
.isEmpty());
498 * Change the adapted directory for a new one
499 * @param directory New file to adapt. Can be NULL, meaning
500 * "no content to adapt".
501 * @param updatedStorageManager Optional updated storage manager; used to replace
502 * mStorageManager if is different (and not NULL)
504 public void swapDirectory(OCFile directory
, FileDataStorageManager updatedStorageManager
) {
506 if (updatedStorageManager
!= null
&& updatedStorageManager
!= mStorageManager
) {
507 mStorageManager
= updatedStorageManager
;
508 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
510 if (mStorageManager
!= null
) {
511 mFiles
= mStorageManager
.getFolderContent(mFile
);
513 mFiles
= getFolders(mFiles
);
518 notifyDataSetChanged();
523 * Filter for getting only the folders
525 * @return Vector<OCFile>
527 public Vector
<OCFile
> getFolders(Vector
<OCFile
> files
) {
528 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
529 OCFile current
= null
;
530 for (int i
=0; i
<files
.size(); i
++) {
531 current
= files
.get(i
);
532 if (current
.isFolder()) {
541 * Check if parent folder does not include 'S' permission and if file/folder
544 * @param file: OCFile
545 * @return boolean: True if it is shared with me and false if it is not
547 private boolean checkIfFileIsSharedWithMe(OCFile file
) {
548 return (mFile
.getPermissions() != null
549 && !mFile
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
)
550 && file
.getPermissions() != null
551 && file
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
));