arnaucube
arnaucube/openEventsPlatformAppPublic Self-hosted repository
openEventsPlatformApp/plugins/cordova-plugin-file/src/android/ContentFilesystem.java
plugins/cordova-plugin-file/src/android/ContentFilesystem.javaRaw
  1/*
  2       Licensed to the Apache Software Foundation (ASF) under one
  3       or more contributor license agreements.  See the NOTICE file
  4       distributed with this work for additional information
  5       regarding copyright ownership.  The ASF licenses this file
  6       to you under the Apache License, Version 2.0 (the
  7       "License"); you may not use this file except in compliance
  8       with the License.  You may obtain a copy of the License at
  9
 10         http://www.apache.org/licenses/LICENSE-2.0
 11
 12       Unless required by applicable law or agreed to in writing,
 13       software distributed under the License is distributed on an
 14       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 15       KIND, either express or implied.  See the License for the
 16       specific language governing permissions and limitations
 17       under the License.
 18 */
 19package org.apache.cordova.file;
 20
 21import android.content.ContentResolver;
 22import android.content.Context;
 23import android.database.Cursor;
 24import android.net.Uri;
 25import android.provider.DocumentsContract;
 26import android.provider.MediaStore;
 27import android.provider.OpenableColumns;
 28import java.io.File;
 29import java.io.FileNotFoundException;
 30import java.io.IOException;
 31import org.apache.cordova.CordovaResourceApi;
 32import org.json.JSONException;
 33import org.json.JSONObject;
 34
 35public class ContentFilesystem extends Filesystem {
 36
 37    private final Context context;
 38
 39	public ContentFilesystem(Context context, CordovaResourceApi resourceApi) {
 40		super(Uri.parse("content://"), "content", resourceApi);
 41        this.context = context;
 42	}
 43
 44    @Override
 45    public Uri toNativeUri(LocalFilesystemURL inputURL) {
 46        String authorityAndPath = inputURL.uri.getEncodedPath().substring(this.name.length() + 2);
 47        if (authorityAndPath.length() < 2) {
 48            return null;
 49        }
 50        String ret = "content://" + authorityAndPath;
 51        String query = inputURL.uri.getEncodedQuery();
 52        if (query != null) {
 53            ret += '?' + query;
 54        }
 55        String frag = inputURL.uri.getEncodedFragment();
 56        if (frag != null) {
 57            ret += '#' + frag;
 58        }
 59        return Uri.parse(ret);
 60    }
 61
 62    @Override
 63    public LocalFilesystemURL toLocalUri(Uri inputURL) {
 64        if (!"content".equals(inputURL.getScheme())) {
 65            return null;
 66        }
 67        String subPath = inputURL.getEncodedPath();
 68        if (subPath.length() > 0) {
 69            subPath = subPath.substring(1);
 70        }
 71        Uri.Builder b = new Uri.Builder()
 72            .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
 73            .authority("localhost")
 74            .path(name)
 75            .appendPath(inputURL.getAuthority());
 76        if (subPath.length() > 0) {
 77            b.appendEncodedPath(subPath);
 78        }
 79        Uri localUri = b.encodedQuery(inputURL.getEncodedQuery())
 80            .encodedFragment(inputURL.getEncodedFragment())
 81            .build();
 82        return LocalFilesystemURL.parse(localUri);
 83    }
 84
 85    @Override
 86	public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
 87			String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException {
 88        throw new UnsupportedOperationException("getFile() not supported for content:. Use resolveLocalFileSystemURL instead.");
 89	}
 90
 91	@Override
 92	public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL)
 93			throws NoModificationAllowedException {
 94        Uri contentUri = toNativeUri(inputURL);
 95		try {
 96            context.getContentResolver().delete(contentUri, null, null);
 97		} catch (UnsupportedOperationException t) {
 98			// Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator.
 99			// The ContentResolver applies only when the file was registered in the
100			// first case, which is generally only the case with images.
101            NoModificationAllowedException nmae = new NoModificationAllowedException("Deleting not supported for content uri: " + contentUri);
102            nmae.initCause(t);
103            throw nmae;
104		}
105        return true;
106	}
107
108	@Override
109	public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL)
110			throws NoModificationAllowedException {
111		throw new NoModificationAllowedException("Cannot remove content url");
112	}
113
114    @Override
115    public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
116        throw new UnsupportedOperationException("readEntriesAtLocalURL() not supported for content:. Use resolveLocalFileSystemURL instead.");
117    }
118
119	@Override
120	public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
121        long size = -1;
122        long lastModified = 0;
123        Uri nativeUri = toNativeUri(inputURL);
124        String mimeType = resourceApi.getMimeType(nativeUri);
125        Cursor cursor = openCursorForURL(nativeUri);
126        try {
127            if (cursor != null && cursor.moveToFirst()) {
128                Long sizeForCursor = resourceSizeForCursor(cursor);
129                if (sizeForCursor != null) {
130                    size = sizeForCursor.longValue();
131                }
132                Long modified = lastModifiedDateForCursor(cursor);
133                if (modified != null)
134                    lastModified = modified.longValue();
135            } else {
136                // Some content providers don't support cursors at all!
137                CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(nativeUri);
138                size = offr.length;
139            }
140        } catch (IOException e) {
141            FileNotFoundException fnfe = new FileNotFoundException();
142            fnfe.initCause(e);
143            throw fnfe;
144        } finally {
145        	if (cursor != null)
146        		cursor.close();
147        }
148
149        JSONObject metadata = new JSONObject();
150        try {
151        	metadata.put("size", size);
152        	metadata.put("type", mimeType);
153        	metadata.put("name", name);
154        	metadata.put("fullPath", inputURL.path);
155        	metadata.put("lastModifiedDate", lastModified);
156        } catch (JSONException e) {
157        	return null;
158        }
159        return metadata;
160	}
161
162	@Override
163	public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
164			int offset, boolean isBinary) throws NoModificationAllowedException {
165        throw new NoModificationAllowedException("Couldn't write to file given its content URI");
166    }
167	@Override
168	public long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
169			throws NoModificationAllowedException {
170        throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
171	}
172
173	protected Cursor openCursorForURL(Uri nativeUri) {
174        ContentResolver contentResolver = context.getContentResolver();
175        try {
176            return contentResolver.query(nativeUri, null, null, null, null);
177        } catch (UnsupportedOperationException e) {
178            return null;
179        }
180	}
181
182	private Long resourceSizeForCursor(Cursor cursor) {
183        int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
184        if (columnIndex != -1) {
185            String sizeStr = cursor.getString(columnIndex);
186            if (sizeStr != null) {
187            	return Long.parseLong(sizeStr);
188            }
189        }
190        return null;
191	}
192	
193	protected Long lastModifiedDateForCursor(Cursor cursor) {
194        int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED);
195        if (columnIndex == -1) {
196            columnIndex = cursor.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED);
197        }
198        if (columnIndex != -1) {
199            String dateStr = cursor.getString(columnIndex);
200            if (dateStr != null) {
201                return Long.parseLong(dateStr);
202            }
203        }
204        return null;
205	}
206
207    @Override
208    public String filesystemPathForURL(LocalFilesystemURL url) {
209        File f = resourceApi.mapUriToFile(toNativeUri(url));
210        return f == null ? null : f.getAbsolutePath();
211    }
212
213	@Override
214	public LocalFilesystemURL URLforFilesystemPath(String path) {
215		// Returns null as we don't support reverse mapping back to content:// URLs
216		return null;
217	}
218
219	@Override
220	public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
221		return true;
222	}
223}