03f5ddc795680bc67a76850a5e5e02f5fc344310
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / adapter / FileListListAdapter.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
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.
8 *
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.
13 *
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/>.
16 *
17 */
18 package com.owncloud.android.ui.adapter;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.net.URLEncoder;
23 import java.util.Vector;
24
25 import android.accounts.Account;
26 import android.accounts.AuthenticatorException;
27 import android.accounts.OperationCanceledException;
28 import android.content.Context;
29 import android.content.res.Resources;
30 import android.graphics.Bitmap;
31 <<<<<<< HEAD
32 import android.graphics.Bitmap.CompressFormat;
33 import android.graphics.BitmapFactory;
34 import android.media.ThumbnailUtils;
35 import android.os.AsyncTask;
36 =======
37 import android.graphics.BitmapFactory;
38 import android.media.ThumbnailUtils;
39 >>>>>>> c0dc4c42d71eb9593ff48a02a8af74bd7df8776e
40 import android.util.TypedValue;
41 import android.view.LayoutInflater;
42 import android.view.View;
43 import android.view.ViewGroup;
44 import android.widget.BaseAdapter;
45 import android.widget.ImageView;
46 import android.widget.ListAdapter;
47 import android.widget.ListView;
48 import android.widget.TextView;
49
50 import com.owncloud.android.R;
51 import com.owncloud.android.authentication.AccountUtils;
52 import com.owncloud.android.datamodel.FileDataStorageManager;
53 import com.owncloud.android.datamodel.OCFile;
54 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
55 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
56 import com.owncloud.android.lib.common.OwnCloudAccount;
57 import com.owncloud.android.lib.common.OwnCloudClient;
58 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
59 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
60 import com.owncloud.android.ui.activity.ComponentsGetter;
61 import com.owncloud.android.utils.DisplayUtils;
62
63 import org.apache.http.HttpEntity;
64 import org.apache.http.HttpResponse;
65 import org.apache.http.auth.AuthScope;
66 import org.apache.http.auth.UsernamePasswordCredentials;
67 import org.apache.http.client.methods.HttpGet;
68 import org.apache.http.impl.client.DefaultHttpClient;
69 import org.apache.http.util.EntityUtils;
70
71
72 /**
73 * This Adapter populates a ListView with all files and folders in an ownCloud
74 * instance.
75 *
76 * @author Bartek Przybylski
77 *
78 */
79 public class FileListListAdapter extends BaseAdapter implements ListAdapter {
80 private final static String PERMISSION_SHARED_WITH_ME = "S";
81
82 private Context mContext;
83 private OCFile mFile = null;
84 private Vector<OCFile> mFiles = null;
85
86 private FileDataStorageManager mStorageManager;
87 private Account mAccount;
88 private ComponentsGetter mTransferServiceGetter;
89 private final Object mDiskCacheLock = new Object();
90 private DiskLruImageCache mDiskLruCache;
91 private boolean mDiskCacheStarting = true;
92 private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
93 private CompressFormat mCompressFormat = CompressFormat.JPEG;
94 private int mCompressQuality = 70;
95 private OwnCloudClient mClient;
96
97 public FileListListAdapter(Context context, ComponentsGetter transferServiceGetter) {
98 mContext = context;
99 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
100 mTransferServiceGetter = transferServiceGetter;
101
102 // Initialise disk cache on background thread
103 new InitDiskCacheTask().execute();
104 }
105
106 class InitDiskCacheTask extends AsyncTask<File, Void, Void> {
107 @Override
108 protected Void doInBackground(File... params) {
109 synchronized (mDiskCacheLock) {
110 mDiskLruCache = new DiskLruImageCache(mContext, "thumbnailCache", DISK_CACHE_SIZE, mCompressFormat,mCompressQuality);
111
112 try {
113 OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, mContext);
114 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().
115 getClientFor(ocAccount, mContext);
116 } catch (AccountNotFoundException e) {
117 // TODO Auto-generated catch block
118 e.printStackTrace();
119 } catch (AuthenticatorException e) {
120 // TODO Auto-generated catch block
121 e.printStackTrace();
122 } catch (OperationCanceledException e) {
123 // TODO Auto-generated catch block
124 e.printStackTrace();
125 } catch (IOException e) {
126 // TODO Auto-generated catch block
127 e.printStackTrace();
128 }
129
130 mDiskCacheStarting = false; // Finished initialization
131 mDiskCacheLock.notifyAll(); // Wake any waiting threads
132 }
133 return null;
134 }
135 }
136
137 class BitmapWorkerTask extends AsyncTask<OCFile, Void, Bitmap> {
138 private final ImageView fileIcon;
139
140 public BitmapWorkerTask(ImageView fileIcon) {
141 this.fileIcon = fileIcon;
142 }
143
144 // Decode image in background.
145 @Override
146 protected Bitmap doInBackground(OCFile... params) {
147 OCFile file = params[0];
148 final String imageKey = String.valueOf(file.getRemoteId());
149
150 // Check disk cache in background thread
151 Bitmap thumbnail = getBitmapFromDiskCache(imageKey);
152
153 // Not found in disk cache
154 if (thumbnail == null) {
155 // Converts dp to pixel
156 Resources r = mContext.getResources();
157 int px = (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics()));
158
159 if (file.isDown()){
160 Bitmap bitmap = BitmapFactory.decodeFile(file.getStoragePath());
161 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
162
163 // Add thumbnail to cache
164 addBitmapToCache(imageKey, thumbnail);
165
166 } else {
167 // Download thumbnail from server
168 DefaultHttpClient httpclient = new DefaultHttpClient();
169 try {
170 httpclient.getCredentialsProvider().setCredentials(
171 new AuthScope(mClient.getBaseUri().toString().replace("https://", ""), 443),
172 new UsernamePasswordCredentials(mClient.getCredentials().getUsername(), mClient.getCredentials().getAuthToken()));
173
174
175 // TODO change to user preview.png
176 HttpGet httpget = new HttpGet(mClient.getBaseUri() + "/ocs/v1.php/thumbnail?path=" + URLEncoder.encode(file.getRemotePath(), "UTF-8"));
177 HttpResponse response = httpclient.execute(httpget);
178 HttpEntity entity = response.getEntity();
179
180 if (entity != null) {
181 byte[] bytes = EntityUtils.toByteArray(entity);
182 Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
183 thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px);
184
185 // Add thumbnail to cache
186 if (thumbnail != null){
187 addBitmapToCache(imageKey, thumbnail);
188 }
189
190 }
191 } catch(Exception e){
192 e.printStackTrace();
193 }finally {
194 httpclient.getConnectionManager().shutdown();
195 }
196 }
197 }
198 return thumbnail;
199 }
200
201 protected void onPostExecute(Bitmap bitmap){
202 fileIcon.setImageBitmap(bitmap);
203 }
204 }
205
206 public void addBitmapToCache(String key, Bitmap bitmap) {
207 synchronized (mDiskCacheLock) {
208 if (mDiskLruCache != null && mDiskLruCache.getBitmap(key) == null) {
209 mDiskLruCache.put(key, bitmap);
210 }
211 }
212 }
213
214 public Bitmap getBitmapFromDiskCache(String key) {
215 synchronized (mDiskCacheLock) {
216 // Wait while disk cache is started from background thread
217 while (mDiskCacheStarting) {
218 try {
219 mDiskCacheLock.wait();
220 } catch (InterruptedException e) {}
221 }
222 if (mDiskLruCache != null) {
223 return (Bitmap) mDiskLruCache.getBitmap(key);
224 }
225 }
226 return null;
227 }
228
229 @Override
230 public boolean areAllItemsEnabled() {
231 return true;
232 }
233
234 @Override
235 public boolean isEnabled(int position) {
236 return true;
237 }
238
239 @Override
240 public int getCount() {
241 return mFiles != null ? mFiles.size() : 0;
242 }
243
244 @Override
245 public Object getItem(int position) {
246 if (mFiles == null || mFiles.size() <= position)
247 return null;
248 return mFiles.get(position);
249 }
250
251 @Override
252 public long getItemId(int position) {
253 if (mFiles == null || mFiles.size() <= position)
254 return 0;
255 return mFiles.get(position).getFileId();
256 }
257
258 @Override
259 public int getItemViewType(int position) {
260 return 0;
261 }
262
263 @Override
264 public View getView(int position, View convertView, ViewGroup parent) {
265 View view = convertView;
266 if (view == null) {
267 LayoutInflater inflator = (LayoutInflater) mContext
268 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
269 view = inflator.inflate(R.layout.list_item, null);
270 }
271
272 if (mFiles != null && mFiles.size() > position) {
273 OCFile file = mFiles.get(position);
274 TextView fileName = (TextView) view.findViewById(R.id.Filename);
275 String name = file.getFileName();
276
277 fileName.setText(name);
278 ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);
279 ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
280 ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
281 sharedWithMeIconV.setVisibility(View.GONE);
282
283 ImageView localStateView = (ImageView) view.findViewById(R.id.imageView2);
284 localStateView.bringToFront();
285 FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder();
286 FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
287 if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file)) {
288 localStateView.setImageResource(R.drawable.downloading_file_indicator);
289 localStateView.setVisibility(View.VISIBLE);
290 } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
291 localStateView.setImageResource(R.drawable.uploading_file_indicator);
292 localStateView.setVisibility(View.VISIBLE);
293 } else if (file.isDown()) {
294 localStateView.setImageResource(R.drawable.local_file_indicator);
295 localStateView.setVisibility(View.VISIBLE);
296 } else {
297 localStateView.setVisibility(View.INVISIBLE);
298 }
299
300 TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
301 TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
302 ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);
303
304 if (!file.isFolder()) {
305 fileSizeV.setVisibility(View.VISIBLE);
306 fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
307 lastModV.setVisibility(View.VISIBLE);
308 lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
309 // this if-else is needed even thoe fav icon is visible by default
310 // because android reuses views in listview
311 if (!file.keepInSync()) {
312 view.findViewById(R.id.imageView3).setVisibility(View.GONE);
313 } else {
314 view.findViewById(R.id.imageView3).setVisibility(View.VISIBLE);
315 }
316
317 ListView parentList = (ListView)parent;
318 if (parentList.getChoiceMode() == ListView.CHOICE_MODE_NONE) {
319 checkBoxV.setVisibility(View.GONE);
320 } else {
321 if (parentList.isItemChecked(position)) {
322 checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
323 } else {
324 checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
325 }
326 checkBoxV.setVisibility(View.VISIBLE);
327 }
328 <<<<<<< HEAD
329
330 // first set thumbnail according to Mimetype, prevents empty thumbnails
331 fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
332
333 // get Thumbnail if file is image
334 if (file.isImage()){
335 // Thumbnail in Cache?
336 Bitmap thumbnail = getBitmapFromDiskCache(String.valueOf(file.getRemoteId()));
337 if (thumbnail != null){
338 fileIcon.setImageBitmap(thumbnail);
339 } else {
340 // generate new Thumbnail
341 new BitmapWorkerTask(fileIcon).execute(file);
342 }
343 }
344
345 =======
346
347 // generate Thumbnail if file is available local and image
348 if (file.isDown() && file.isImage()){
349 // Converts dp to pixel
350 Resources r = mContext.getResources();
351 int px = (int) Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics()));
352 Bitmap bitmap = BitmapFactory.decodeFile(file.getStoragePath());
353 fileIcon.setImageBitmap(ThumbnailUtils.extractThumbnail(bitmap, px, px));
354 } else {
355 fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
356 }
357
358 >>>>>>> c0dc4c42d71eb9593ff48a02a8af74bd7df8776e
359 if (checkIfFileIsSharedWithMe(file)) {
360 sharedWithMeIconV.setVisibility(View.VISIBLE);
361 }
362 }
363 else {
364 fileSizeV.setVisibility(View.INVISIBLE);
365 //fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
366 lastModV.setVisibility(View.VISIBLE);
367 lastModV.setText(DisplayUtils.unixTimeToHumanReadable(file.getModificationTimestamp()));
368 checkBoxV.setVisibility(View.GONE);
369 view.findViewById(R.id.imageView3).setVisibility(View.GONE);
370
371 if (checkIfFileIsSharedWithMe(file)) {
372 fileIcon.setImageResource(R.drawable.shared_with_me_folder);
373 sharedWithMeIconV.setVisibility(View.VISIBLE);
374 } else {
375 fileIcon.setImageResource(DisplayUtils.getResourceId(file.getMimetype(), file.getFileName()));
376 }
377
378 // If folder is sharedByLink, icon folder must be changed to
379 // folder-public one
380 if (file.isShareByLink()) {
381 fileIcon.setImageResource(R.drawable.folder_public);
382 }
383 }
384
385 if (file.isShareByLink()) {
386 sharedIconV.setVisibility(View.VISIBLE);
387 } else {
388 sharedIconV.setVisibility(View.GONE);
389 }
390 }
391
392 return view;
393 }
394
395 @Override
396 public int getViewTypeCount() {
397 return 1;
398 }
399
400 @Override
401 public boolean hasStableIds() {
402 return true;
403 }
404
405 @Override
406 public boolean isEmpty() {
407 return (mFiles == null || mFiles.isEmpty());
408 }
409
410 /**
411 * Change the adapted directory for a new one
412 * @param directory New file to adapt. Can be NULL, meaning "no content to adapt".
413 * @param updatedStorageManager Optional updated storage manager; used to replace mStorageManager if is different (and not NULL)
414 */
415 public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) {
416 mFile = directory;
417 if (updatedStorageManager != null && updatedStorageManager != mStorageManager) {
418 mStorageManager = updatedStorageManager;
419 mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
420 }
421 if (mStorageManager != null) {
422 mFiles = mStorageManager.getFolderContent(mFile);
423 } else {
424 mFiles = null;
425 }
426 notifyDataSetChanged();
427 }
428
429 /**
430 * Check if parent folder does not include 'S' permission and if file/folder
431 * is shared with me
432 *
433 * @param file: OCFile
434 * @return boolean: True if it is shared with me and false if it is not
435 */
436 private boolean checkIfFileIsSharedWithMe(OCFile file) {
437 return (mFile.getPermissions() != null && !mFile.getPermissions().contains(PERMISSION_SHARED_WITH_ME)
438 && file.getPermissions() != null && file.getPermissions().contains(PERMISSION_SHARED_WITH_ME));
439 }
440 }