beb08c79f434eb76820b71060098d7e1e957f2b3
[pub/Android/ownCloud.git] / src / com / owncloud / android / utils / DisplayUtils.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 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
19 package com.owncloud.android.utils;
20
21 import java.net.IDN;
22 import java.util.Arrays;
23 import java.util.Calendar;
24 import java.util.Date;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.Set;
28
29 import android.annotation.TargetApi;
30 import android.content.Context;
31 import android.os.Build;
32 import android.text.format.DateUtils;
33
34 import com.owncloud.android.MainApp;
35 import com.owncloud.android.R;
36 import com.owncloud.android.datamodel.OCFile;
37
38 /**
39 * A helper class for some string operations.
40 *
41 * @author Bartek Przybylski
42 * @author David A. Velasco
43 */
44 public class DisplayUtils {
45
46 private static final String OWNCLOUD_APP_NAME = "ownCloud";
47
48 //private static String TAG = DisplayUtils.class.getSimpleName();
49
50 private static final String[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
51
52 private static HashMap<String, String> mimeType2HUmanReadable;
53 static {
54 mimeType2HUmanReadable = new HashMap<String, String>();
55 // images
56 mimeType2HUmanReadable.put("image/jpeg", "JPEG image");
57 mimeType2HUmanReadable.put("image/jpg", "JPEG image");
58 mimeType2HUmanReadable.put("image/png", "PNG image");
59 mimeType2HUmanReadable.put("image/bmp", "Bitmap image");
60 mimeType2HUmanReadable.put("image/gif", "GIF image");
61 mimeType2HUmanReadable.put("image/svg+xml", "JPEG image");
62 mimeType2HUmanReadable.put("image/tiff", "TIFF image");
63 // music
64 mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file");
65 mimeType2HUmanReadable.put("application/ogg", "OGG music file");
66
67 }
68
69 private static final String TYPE_APPLICATION = "application";
70 private static final String TYPE_AUDIO = "audio";
71 private static final String TYPE_IMAGE = "image";
72 private static final String TYPE_TXT = "text";
73 private static final String TYPE_VIDEO = "video";
74
75 private static final String SUBTYPE_PDF = "pdf";
76 private static final String SUBTYPE_XML = "xml";
77 private static final String[] SUBTYPES_DOCUMENT = { "msword",
78 "vnd.openxmlformats-officedocument.wordprocessingml.document",
79 "vnd.oasis.opendocument.text",
80 "rtf"
81 };
82 private static Set<String> SUBTYPES_DOCUMENT_SET = new HashSet<String>(Arrays.asList(SUBTYPES_DOCUMENT));
83 private static final String[] SUBTYPES_SPREADSHEET = { "msexcel",
84 "vnd.openxmlformats-officedocument.spreadsheetml.sheet",
85 "vnd.oasis.opendocument.spreadsheet"
86 };
87 private static Set<String> SUBTYPES_SPREADSHEET_SET = new HashSet<String>(Arrays.asList(SUBTYPES_SPREADSHEET));
88 private static final String[] SUBTYPES_PRESENTATION = { "mspowerpoint",
89 "vnd.openxmlformats-officedocument.presentationml.presentation",
90 "vnd.oasis.opendocument.presentation"
91 };
92 private static Set<String> SUBTYPES_PRESENTATION_SET = new HashSet<String>(Arrays.asList(SUBTYPES_PRESENTATION));
93 private static final String[] SUBTYPES_COMPRESSED = {"x-tar", "x-gzip", "zip"};
94 private static final Set<String> SUBTYPES_COMPRESSED_SET = new HashSet<String>(Arrays.asList(SUBTYPES_COMPRESSED));
95 private static final String SUBTYPE_OCTET_STREAM = "octet-stream";
96 private static final String EXTENSION_RAR = "rar";
97 private static final String EXTENSION_RTF = "rtf";
98 private static final String EXTENSION_3GP = "3gp";
99
100 /**
101 * Converts the file size in bytes to human readable output.
102 *
103 * @param bytes Input file size
104 * @return Like something readable like "12 MB"
105 */
106 public static String bytesToHumanReadable(long bytes) {
107 double result = bytes;
108 int attachedsuff = 0;
109 while (result > 1024 && attachedsuff < sizeSuffixes.length) {
110 result /= 1024.;
111 attachedsuff++;
112 }
113 result = ((int) (result * 100)) / 100.;
114 return result + " " + sizeSuffixes[attachedsuff];
115 }
116
117 /**
118 * Removes special HTML entities from a string
119 *
120 * @param s Input string
121 * @return A cleaned version of the string
122 */
123 public static String HtmlDecode(String s) {
124 /*
125 * TODO: Perhaps we should use something more proven like:
126 * http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#unescapeHtml%28java.lang.String%29
127 */
128
129 String ret = "";
130 for (int i = 0; i < s.length(); ++i) {
131 if (s.charAt(i) == '%') {
132 ret += (char) Integer.parseInt(s.substring(i + 1, i + 3), 16);
133 i += 2;
134 } else {
135 ret += s.charAt(i);
136 }
137 }
138 return ret;
139 }
140
141 /**
142 * Converts MIME types like "image/jpg" to more end user friendly output
143 * like "JPG image".
144 *
145 * @param mimetype MIME type to convert
146 * @return A human friendly version of the MIME type
147 */
148 public static String convertMIMEtoPrettyPrint(String mimetype) {
149 if (mimeType2HUmanReadable.containsKey(mimetype)) {
150 return mimeType2HUmanReadable.get(mimetype);
151 }
152 if (mimetype.split("/").length >= 2)
153 return mimetype.split("/")[1].toUpperCase() + " file";
154 return "Unknown type";
155 }
156
157
158 /**
159 * Returns the resource identifier of an image resource to use as icon associated to a
160 * known MIME type.
161 *
162 * @param mimetype MIME type string.
163 * @param filename name, with extension
164 * @return Resource identifier of an image resource.
165 */
166 public static int getResourceId(String mimetype, String filename) {
167
168 if (mimetype == null) {
169 return R.drawable.file;
170
171 } else if ("DIR".equals(mimetype)) {
172 return R.drawable.ic_menu_archive;
173
174 } else {
175 String [] parts = mimetype.split("/");
176 String type = parts[0];
177 String subtype = (parts.length > 1) ? parts[1] : "";
178
179 if(TYPE_TXT.equals(type)) {
180 return R.drawable.file_doc;
181
182 } else if(TYPE_IMAGE.equals(type)) {
183 return R.drawable.file_image;
184
185 } else if(TYPE_VIDEO.equals(type)) {
186 return R.drawable.file_movie;
187
188 } else if(TYPE_AUDIO.equals(type)) {
189 return R.drawable.file_sound;
190
191 } else if(TYPE_APPLICATION.equals(type)) {
192
193 if (SUBTYPE_PDF.equals(subtype)) {
194 return R.drawable.file_pdf;
195
196 } else if (SUBTYPE_XML.equals(subtype)) {
197 return R.drawable.file_doc;
198
199 } else if (SUBTYPES_DOCUMENT_SET.contains(subtype)) {
200 return R.drawable.file_doc;
201
202 } else if (SUBTYPES_SPREADSHEET_SET.contains(subtype)) {
203 return R.drawable.file_xls;
204
205 } else if (SUBTYPES_PRESENTATION_SET.contains(subtype)) {
206 return R.drawable.file_ppt;
207
208 } else if (SUBTYPES_COMPRESSED_SET.contains(subtype)) {
209 return R.drawable.file_zip;
210
211 } else if (SUBTYPE_OCTET_STREAM.equals(subtype) ) {
212 if (getExtension(filename).equalsIgnoreCase(EXTENSION_RAR)) {
213 return R.drawable.file_zip;
214
215 } else if (getExtension(filename).equalsIgnoreCase(EXTENSION_RTF)) {
216 return R.drawable.file_doc;
217
218 } else if (getExtension(filename).equalsIgnoreCase(EXTENSION_3GP)) {
219 return R.drawable.file_movie;
220
221 }
222 }
223 }
224 }
225
226 // default icon
227 return R.drawable.file;
228 }
229
230
231 private static String getExtension(String filename) {
232 String extension = filename.substring(filename.lastIndexOf(".") + 1);
233
234 return extension;
235 }
236
237 /**
238 * Converts Unix time to human readable format
239 * @param miliseconds that have passed since 01/01/1970
240 * @return The human readable time for the users locale
241 */
242 public static String unixTimeToHumanReadable(long milliseconds) {
243 Date date = new Date(milliseconds);
244 return date.toLocaleString();
245 }
246
247
248 public static int getSeasonalIconId() {
249 if (Calendar.getInstance().get(Calendar.DAY_OF_YEAR) >= 354 &&
250 MainApp.getAppContext().getString(R.string.app_name).equals(OWNCLOUD_APP_NAME)) {
251 return R.drawable.winter_holidays_icon;
252 } else {
253 return R.drawable.icon;
254 }
255 }
256
257 /**
258 * Converts an internationalized domain name (IDN) in an URL to and from ASCII/Unicode.
259 * @param url the URL where the domain name should be converted
260 * @param toASCII if true converts from Unicode to ASCII, if false converts from ASCII to Unicode
261 * @return the URL containing the converted domain name
262 */
263 @TargetApi(Build.VERSION_CODES.GINGERBREAD)
264 public static String convertIdn(String url, boolean toASCII) {
265
266 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
267 // Find host name after '//' or '@'
268 int hostStart = 0;
269 if (url.indexOf("//") != -1) {
270 hostStart = url.indexOf("//") + "//".length();
271 } else if (url.indexOf("@") != -1) {
272 hostStart = url.indexOf("@") + "@".length();
273 }
274
275 int hostEnd = url.substring(hostStart).indexOf("/");
276 // Handle URL which doesn't have a path (path is implicitly '/')
277 hostEnd = (hostEnd == -1 ? url.length() : hostStart + hostEnd);
278
279 String host = url.substring(hostStart, hostEnd);
280 host = (toASCII ? IDN.toASCII(host) : IDN.toUnicode(host));
281
282 return url.substring(0, hostStart) + host + url.substring(hostEnd);
283 } else {
284 return url;
285 }
286 }
287
288 /**
289 * Get the file extension if it is on path as type "content://.../DocInfo.doc"
290 * @param filepath: Content Uri converted to string format
291 * @return String: fileExtension (type '.pdf'). Empty if no extension
292 */
293 public static String getComposedFileExtension(String filepath) {
294 String fileExtension = "";
295 String fileNameInContentUri = filepath.substring(filepath.lastIndexOf("/"));
296
297 // Check if extension is included in uri
298 int pos = fileNameInContentUri.lastIndexOf('.');
299 if (pos >= 0) {
300 fileExtension = fileNameInContentUri.substring(pos);
301 }
302 return fileExtension;
303 }
304
305 public static CharSequence getRelativeDateTimeString(Context c, long time, long minResolution, long transitionResolution, int flags){
306 CharSequence dateString = "";
307
308 // in Future
309 if (time > System.currentTimeMillis()){
310 return DisplayUtils.unixTimeToHumanReadable(time);
311 }
312 // < 60 seconds -> seconds ago
313 else if ((System.currentTimeMillis() - time) < 60 * 1000) {
314 return c.getString(R.string.file_list_seconds_ago);
315 } else {
316 // Workaround 2.x bug (see https://github.com/owncloud/android/issues/716)
317 if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB && (System.currentTimeMillis() - time) > 24 * 60 * 60 * 1000){
318 Date date = new Date(time);
319 date.setHours(0);
320 date.setMinutes(0);
321 date.setSeconds(0);
322 dateString = DateUtils.getRelativeDateTimeString(c, date.getTime(), minResolution, transitionResolution, flags);
323 } else {
324 dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags);
325 }
326 }
327
328 return dateString.toString().split(",")[0];
329 }
330
331 /**
332 * Update the passed path removing the last "/" if it is not the root folder
333 * @param path
334 */
335 public static String getPathWithoutLastSlash(String path) {
336
337 // Remove last slash from path
338 if (path.length() > 1 && path.charAt(path.length()-1) == OCFile.PATH_SEPARATOR.charAt(0)) {
339 path = path.substring(0, path.length()-1);
340 }
341 return path;
342 }
343 }