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(status
== HttpStatus
.SC_OK
) {
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 protected void onPostExecute(Bitmap bitmap
){
248 if (imageViewReference
!= null
&& bitmap
!= null
) {
249 final ImageView imageView
= imageViewReference
.get();
250 final ThumbnailGenerationTask bitmapWorkerTask
=
251 getBitmapWorkerTask(imageView
);
252 if (this == bitmapWorkerTask
&& imageView
!= null
) {
253 imageView
.setImageBitmap(bitmap
);
259 public void addBitmapToCache(String key
, Bitmap bitmap
) {
260 synchronized (thumbnailDiskCacheLock
) {
261 if (mThumbnailCache
!= null
&& mThumbnailCache
.getBitmap(key
) == null
) {
262 mThumbnailCache
.put(key
, bitmap
);
267 public Bitmap
getBitmapFromDiskCache(String key
) {
268 synchronized (thumbnailDiskCacheLock
) {
269 // Wait while disk cache is started from background thread
270 while (mThumbnailCacheStarting
) {
272 thumbnailDiskCacheLock
.wait();
273 } catch (InterruptedException e
) {}
275 if (mThumbnailCache
!= null
) {
276 return (Bitmap
) mThumbnailCache
.getBitmap(key
);
283 public boolean areAllItemsEnabled() {
288 public boolean isEnabled(int position
) {
293 public int getCount() {
294 return mFiles
!= null ? mFiles
.size() : 0;
298 public Object
getItem(int position
) {
299 if (mFiles
== null
|| mFiles
.size() <= position
)
301 return mFiles
.get(position
);
305 public long getItemId(int position
) {
306 if (mFiles
== null
|| mFiles
.size() <= position
)
308 return mFiles
.get(position
).getFileId();
312 public int getItemViewType(int position
) {
317 public View
getView(int position
, View convertView
, ViewGroup parent
) {
318 View view
= convertView
;
320 LayoutInflater inflator
= (LayoutInflater
) mContext
321 .getSystemService(Context
.LAYOUT_INFLATER_SERVICE
);
322 view
= inflator
.inflate(R
.layout
.list_item
, null
);
325 if (mFiles
!= null
&& mFiles
.size() > position
) {
326 OCFile file
= mFiles
.get(position
);
327 TextView fileName
= (TextView
) view
.findViewById(R
.id
.Filename
);
328 String name
= file
.getFileName();
330 fileName
.setText(name
);
331 ImageView fileIcon
= (ImageView
) view
.findViewById(R
.id
.imageView1
);
332 ImageView sharedIconV
= (ImageView
) view
.findViewById(R
.id
.sharedIcon
);
333 ImageView sharedWithMeIconV
= (ImageView
) view
.findViewById(R
.id
.sharedWithMeIcon
);
334 sharedWithMeIconV
.setVisibility(View
.GONE
);
336 ImageView localStateView
= (ImageView
) view
.findViewById(R
.id
.imageView2
);
337 localStateView
.bringToFront();
338 FileDownloaderBinder downloaderBinder
=
339 mTransferServiceGetter
.getFileDownloaderBinder();
340 FileUploaderBinder uploaderBinder
= mTransferServiceGetter
.getFileUploaderBinder();
341 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, file
)) {
342 localStateView
.setImageResource(R
.drawable
.downloading_file_indicator
);
343 localStateView
.setVisibility(View
.VISIBLE
);
344 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, file
)) {
345 localStateView
.setImageResource(R
.drawable
.uploading_file_indicator
);
346 localStateView
.setVisibility(View
.VISIBLE
);
347 } else if (file
.isDown()) {
348 localStateView
.setImageResource(R
.drawable
.local_file_indicator
);
349 localStateView
.setVisibility(View
.VISIBLE
);
351 localStateView
.setVisibility(View
.INVISIBLE
);
354 TextView fileSizeV
= (TextView
) view
.findViewById(R
.id
.file_size
);
355 TextView lastModV
= (TextView
) view
.findViewById(R
.id
.last_mod
);
356 ImageView checkBoxV
= (ImageView
) view
.findViewById(R
.id
.custom_checkbox
);
358 if (!file
.isFolder()) {
359 fileSizeV
.setVisibility(View
.VISIBLE
);
360 fileSizeV
.setText(DisplayUtils
.bytesToHumanReadable(file
.getFileLength()));
361 lastModV
.setVisibility(View
.VISIBLE
);
363 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
365 // this if-else is needed even thoe fav icon is visible by default
366 // because android reuses views in listview
367 if (!file
.keepInSync()) {
368 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
370 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.VISIBLE
);
373 ListView parentList
= (ListView
)parent
;
374 if (parentList
.getChoiceMode() == ListView
.CHOICE_MODE_NONE
) {
375 checkBoxV
.setVisibility(View
.GONE
);
377 if (parentList
.isItemChecked(position
)) {
378 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_on_background
);
380 checkBoxV
.setImageResource(android
.R
.drawable
.checkbox_off_background
);
382 checkBoxV
.setVisibility(View
.VISIBLE
);
385 // get Thumbnail if file is image
387 // Thumbnail in Cache?
388 Bitmap thumbnail
= getBitmapFromDiskCache(String
.valueOf(file
.getRemoteId().hashCode()));
389 if (thumbnail
!= null
){
390 fileIcon
.setImageBitmap(thumbnail
);
392 // generate new Thumbnail
393 if (cancelPotentialWork(file
, fileIcon
)) {
394 final ThumbnailGenerationTask task
=
395 new ThumbnailGenerationTask(fileIcon
);
396 final AsyncDrawable asyncDrawable
=
397 new AsyncDrawable(mContext
.getResources(), defaultImg
, task
);
398 fileIcon
.setImageDrawable(asyncDrawable
);
403 fileIcon
.setImageResource(
404 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
408 if (checkIfFileIsSharedWithMe(file
)) {
409 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
413 fileSizeV
.setVisibility(View
.INVISIBLE
);
414 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
415 lastModV
.setVisibility(View
.VISIBLE
);
417 DisplayUtils
.unixTimeToHumanReadable(file
.getModificationTimestamp())
419 checkBoxV
.setVisibility(View
.GONE
);
420 view
.findViewById(R
.id
.imageView3
).setVisibility(View
.GONE
);
422 if (checkIfFileIsSharedWithMe(file
)) {
423 fileIcon
.setImageResource(R
.drawable
.shared_with_me_folder
);
424 sharedWithMeIconV
.setVisibility(View
.VISIBLE
);
426 fileIcon
.setImageResource(
427 DisplayUtils
.getResourceId(file
.getMimetype(), file
.getFileName())
431 // If folder is sharedByLink, icon folder must be changed to
433 if (file
.isShareByLink()) {
434 fileIcon
.setImageResource(R
.drawable
.folder_public
);
438 if (file
.isShareByLink()) {
439 sharedIconV
.setVisibility(View
.VISIBLE
);
441 sharedIconV
.setVisibility(View
.GONE
);
448 public static boolean cancelPotentialWork(OCFile file
, ImageView imageView
) {
449 final ThumbnailGenerationTask bitmapWorkerTask
= getBitmapWorkerTask(imageView
);
451 if (bitmapWorkerTask
!= null
) {
452 final OCFile bitmapData
= bitmapWorkerTask
.file
;
453 // If bitmapData is not yet set or it differs from the new data
454 if (bitmapData
== null
|| bitmapData
!= file
) {
455 // Cancel previous task
456 bitmapWorkerTask
.cancel(true
);
458 // The same work is already in progress
462 // No task associated with the ImageView, or an existing task was cancelled
466 private static ThumbnailGenerationTask
getBitmapWorkerTask(ImageView imageView
) {
467 if (imageView
!= null
) {
468 final Drawable drawable
= imageView
.getDrawable();
469 if (drawable
instanceof AsyncDrawable
) {
470 final AsyncDrawable asyncDrawable
= (AsyncDrawable
) drawable
;
471 return asyncDrawable
.getBitmapWorkerTask();
478 public int getViewTypeCount() {
483 public boolean hasStableIds() {
488 public boolean isEmpty() {
489 return (mFiles
== null
|| mFiles
.isEmpty());
493 * Change the adapted directory for a new one
494 * @param directory New file to adapt. Can be NULL, meaning
495 * "no content to adapt".
496 * @param updatedStorageManager Optional updated storage manager; used to replace
497 * mStorageManager if is different (and not NULL)
499 public void swapDirectory(OCFile directory
, FileDataStorageManager updatedStorageManager
) {
501 if (updatedStorageManager
!= null
&& updatedStorageManager
!= mStorageManager
) {
502 mStorageManager
= updatedStorageManager
;
503 mAccount
= AccountUtils
.getCurrentOwnCloudAccount(mContext
);
505 if (mStorageManager
!= null
) {
506 mFiles
= mStorageManager
.getFolderContent(mFile
);
508 mFiles
= getFolders(mFiles
);
513 notifyDataSetChanged();
518 * Filter for getting only the folders
520 * @return Vector<OCFile>
522 public Vector
<OCFile
> getFolders(Vector
<OCFile
> files
) {
523 Vector
<OCFile
> ret
= new Vector
<OCFile
>();
524 OCFile current
= null
;
525 for (int i
=0; i
<files
.size(); i
++) {
526 current
= files
.get(i
);
527 if (current
.isFolder()) {
536 * Check if parent folder does not include 'S' permission and if file/folder
539 * @param file: OCFile
540 * @return boolean: True if it is shared with me and false if it is not
542 private boolean checkIfFileIsSharedWithMe(OCFile file
) {
543 return (mFile
.getPermissions() != null
544 && !mFile
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
)
545 && file
.getPermissions() != null
546 && file
.getPermissions().contains(PERMISSION_SHARED_WITH_ME
));