Debian Codegraph @

plyer/platforms/android/filechooser.py

raw symbols SCIP
1 '''
2 Android file chooser
3 --------------------
4
5 Android runs ``Activity`` asynchronously via pausing our ``PythonActivity``
6 and starting a new one in the foreground. This means
7 ``AndroidFileChooser._open_file()`` will always return the default value of
8 ``AndroidFileChooser.selection`` i.e. ``None``.
9
10 After the ``Activity`` (for us it's the file chooser ``Intent``) is completed,
11 Android moves it to the background (or destroys or whatever is implemented)
12 and pushes ``PythonActivity`` to the foreground.
13
14 We have a custom listener for ``android.app.Activity.onActivityResult()``
15 via `android` package from `python-for-android` recipe,
16 ``AndroidFileChooser._on_activity_result()`` which is called independently of
17 any our action (we may call anything from our application in Python and this
18 handler will be called nevertheless on each ``android.app.Activity`` result
19 in the system).
20
21 In the handler we check if the ``request_code`` matches the code passed to the
22 ``Context.startActivityForResult()`` i.e. if the result from
23 ``android.app.Activity`` is indeed meant for our ``PythonActivity`` and then we
24 proceed.
25
26 Since the ``android.app.Activity.onActivityResult()`` is the only way for us
27 to intercept the result and we have a handler bound via ``android`` package,
28 we need to get the path/file/... selection to the user the same way.
29
30 Threading + ``Thread.join()`` or ``time.sleep()`` or any other kind of waiting
31 for the result is not an option because:
32
33 1) ``android.app.Activity.onActivityResult()`` might remain unexecuted if
34 the launched file chooser activity does not return the result (``Activity``
35 dies/freezes/etc).
36
37 2) Thread will be still waiting for the result e.g. an update of a value or
38 to actually finish, however the result from the call of
39 ``AndroidFileChooser._open_file()`` will be returned nevertheless and anything
40 using that result will use an incorrect one i.e. the default value of
41 ``AndroidFilechooser.selection`` (``None``).
42
43 .. versionadded:: 1.4.0
44 '''
45
46 from os.path import join, basename
47 from random import randint
48
49 from android import activity, mActivity
50 from jnius import autoclass, cast, JavaException
51 from plyer.facades import FileChooser
52 from plyer import storagepath
53
54 Environment = autoclass("android.os.Environment")
55 String = autoclass('java.lang.String')
56 Intent = autoclass('android.content.Intent')
57 Activity = autoclass('android.app.Activity')
58 DocumentsContract = autoclass('android.provider.DocumentsContract')
59 ContentUris = autoclass('android.content.ContentUris')
60 Uri = autoclass('android.net.Uri')
61 Long = autoclass('java.lang.Long')
62 IMedia = autoclass('android.provider.MediaStore$Images$Media')
63 VMedia = autoclass('android.provider.MediaStore$Video$Media')
64 AMedia = autoclass('android.provider.MediaStore$Audio$Media')
65
66
67 class AndroidFileChooser(FileChooser):
68 '''
69 FileChooser implementation for Android using
70 the built-in file browser via Intent.
71
72 .. versionadded:: 1.4.0
73 '''
74
75 # filechooser activity <-> result pair identification
76 select_code = None
77
78 # default selection value
79 selection = None
80
81 # select multiple files
82 multiple = False
83
84 # mime types
85 mime_type = {
86 "doc": "application/msword",
87 "docx": "application/vnd.openxmlformats-officedocument." +
88 "wordprocessingml.document",
89 "ppt": "application/vnd.ms-powerpoint",
90 "pptx": "application/vnd.openxmlformats-officedocument." +
91 "presentationml.presentation",
92 "xls": "application/vnd.ms-excel",
93 "xlsx": "application/vnd.openxmlformats-officedocument." +
94 "spreadsheetml.sheet",
95 "text": "text/*",
96 "pdf": "application/pdf",
97 "zip": "application/zip",
98 "image": "image/*",
99 "video": "video/*",
100 "audio": "audio/*",
101 "application": "application/*"}
102
103 selected_mime_type = None
104
105 def __init__(self, *args, **kwargs):
106 super().__init__(*args, **kwargs)
107 self.select_code = randint(123456, 654321)
108 self.selection = None
109
110 # bind a function for a response from filechooser activity
111 activity.bind(on_activity_result=self._on_activity_result)
112
113 @staticmethod
114 def _handle_selection(selection):
115 '''
116 Dummy placeholder for returning selection from
117 ``android.app.Activity.onActivityResult()``.
118
119 .. versionadded:: 1.4.0
120 '''
121 return selection
122
123 def _open_file(self, **kwargs):
124 '''
125 Running Android Activity is non-blocking and the only call
126 that blocks is onActivityResult running in GUI thread
127
128 .. versionadded:: 1.4.0
129 '''
130
131 # set up selection handler
132 # startActivityForResult is async
133 # onActivityResult is sync
134 self._handle_selection = kwargs.pop(
135 'on_selection', self._handle_selection
136 )
137 self.selected_mime_type = \
138 kwargs.pop("filters")[0] if "filters" in kwargs else ""
139
140 # create Intent for opening
141 file_intent = Intent(Intent.ACTION_GET_CONTENT)
142 if not self.selected_mime_type or \
143 type(self.selected_mime_type) != str or \
144 self.selected_mime_type not in self.mime_type:
145 file_intent.setType("*/*")
146 else:
147 file_intent.setType(self.mime_type[self.selected_mime_type])
148 file_intent.addCategory(
149 Intent.CATEGORY_OPENABLE
150 )
151
152 # use putExtra to allow multiple file selection
153 if kwargs.get('multiple', self.multiple):
154 file_intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, True)
155
156 # start a new activity from PythonActivity
157 # which creates a filechooser via intent
158 mActivity.startActivityForResult(
159 Intent.createChooser(file_intent, cast(
160 'java.lang.CharSequence',
161 String("FileChooser")
162 )),
163 self.select_code
164 )
165
166 def _on_activity_result(self, request_code, result_code, data):
167 '''
168 Listener for ``android.app.Activity.onActivityResult()`` assigned
169 via ``android.activity.bind()``.
170
171 .. versionadded:: 1.4.0
172 '''
173
174 # not our response
175 if request_code != self.select_code:
176 return
177
178 if result_code != Activity.RESULT_OK:
179 # The action had been cancelled.
180 return
181
182 selection = []
183 # Process multiple URI if multiple files selected
184 try:
185 for count in range(data.getClipData().getItemCount()):
186 ele = self._resolve_uri(
187 data.getClipData().getItemAt(count).getUri()) or []
188 selection.append(ele)
189 except Exception:
190 selection = [self._resolve_uri(data.getData()), ]
191
192 # return value to object
193 self.selection = selection
194 # return value via callback
195 self._handle_selection(selection)
196
197 @staticmethod
198 def _handle_external_documents(uri):
199 '''
200 Selection from the system filechooser when using ``Phone``
201 or ``Internal storage`` or ``SD card`` option from menu.
202
203 .. versionadded:: 1.4.0
204 '''
205
206 file_id = DocumentsContract.getDocumentId(uri)
207 file_type, file_name = file_id.split(':')
208
209 # internal SD card mostly mounted as a files storage in phone
210 internal = storagepath.get_external_storage_dir()
211
212 # external (removable) SD card i.e. microSD
213 external = storagepath.get_sdcard_dir()
214 try:
215 external_base = basename(external)
216 except TypeError:
217 external_base = basename(internal)
218
219 # resolve sdcard path
220 sd_card = internal
221
222 # because external might have /storage/.../1 or other suffix
223 # and file_type might be only a part of the real folder in /storage
224 if file_type in external_base or external_base in file_type:
225 sd_card = external
226 elif file_type == "home":
227 sd_card = join(Environment.getExternalStorageDirectory(
228 ).getAbsolutePath(), Environment.DIRECTORY_DOCUMENTS)
229
230 return join(sd_card, file_name)
231
232 @staticmethod
233 def _handle_media_documents(uri):
234 '''
235 Selection from the system filechooser when using ``Images``
236 or ``Videos`` or ``Audio`` option from menu.
237
238 .. versionadded:: 1.4.0
239 '''
240
241 file_id = DocumentsContract.getDocumentId(uri)
242 file_type, file_name = file_id.split(':')
243 selection = '_id=?'
244
245 if file_type == 'image':
246 uri = IMedia.EXTERNAL_CONTENT_URI
247 elif file_type == 'video':
248 uri = VMedia.EXTERNAL_CONTENT_URI
249 elif file_type == 'audio':
250 uri = AMedia.EXTERNAL_CONTENT_URI
251 return file_name, selection, uri
252
253 @staticmethod
254 def _handle_downloads_documents(uri):
255 '''
256 Selection from the system filechooser when using ``Downloads``
257 option from menu. Might not work all the time due to:
258
259 1) invalid URI:
260
261 jnius.jnius.JavaException:
262 JVM exception occurred: Unknown URI:
263 content://downloads/public_downloads/1034
264
265 2) missing URI / android permissions
266
267 jnius.jnius.JavaException:
268 JVM exception occurred:
269 Permission Denial: reading
270 com.android.providers.downloads.DownloadProvider uri
271 content://downloads/all_downloads/1034 from pid=2532, uid=10455
272 requires android.permission.ACCESS_ALL_DOWNLOADS,
273 or grantUriPermission()
274
275 Workaround:
276 Selecting path from ``Phone`` -> ``Download`` -> ``<file>``
277 (or ``Internal storage``) manually.
278
279 .. versionadded:: 1.4.0
280 '''
281
282 # known locations, differ between machines
283 downloads = [
284 'content://downloads/public_downloads',
285 'content://downloads/my_downloads',
286
287 # all_downloads requires separate permission
288 # android.permission.ACCESS_ALL_DOWNLOADS
289 'content://downloads/all_downloads'
290 ]
291
292 file_id = DocumentsContract.getDocumentId(uri)
293 try_uris = [
294 ContentUris.withAppendedId(
295 Uri.parse(down), Long.valueOf(file_id)
296 )
297 for down in downloads
298 ]
299
300 # try all known Download folder uris
301 # and handle JavaExceptions due to different locations
302 # for content:// downloads or missing permission
303 path = None
304 for down in try_uris:
305 try:
306 path = AndroidFileChooser._parse_content(
307 uri=down, projection=['_data'],
308 selection=None,
309 selection_args=None,
310 sort_order=None
311 )
312
313 except JavaException:
314 import traceback
315 traceback.print_exc()
316
317 # we got a path, ignore the rest
318 if path:
319 break
320
321 # alternative approach to Downloads by joining
322 # all data items from Activity result
323 if not path:
324 for down in try_uris:
325 try:
326 path = AndroidFileChooser._parse_content(
327 uri=down, projection=None,
328 selection=None,
329 selection_args=None,
330 sort_order=None,
331 index_all=True
332 )
333
334 except JavaException:
335 import traceback
336 traceback.print_exc()
337
338 # we got a path, ignore the rest
339 if path:
340 break
341 return path
342
343 def _resolve_uri(self, uri):
344 '''
345 Resolve URI input from ``android.app.Activity.onActivityResult()``.
346
347 .. versionadded:: 1.4.0
348 '''
349
350 uri_authority = uri.getAuthority()
351 uri_scheme = uri.getScheme().lower()
352
353 path = None
354 file_name = None
355 selection = None
356 downloads = None
357
358 # This does not allow file selected from google photos or gallery
359 # or even any other file explorer to work
360 # not a document URI, nothing to convert from
361 # if not DocumentsContract.isDocumentUri(mActivity, uri):
362 # return path
363
364 if uri_authority == 'com.android.externalstorage.documents':
365 return self._handle_external_documents(uri)
366
367 # in case a user selects a file from 'Downloads' section
368 # note: this won't be triggered if a user selects a path directly
369 # e.g.: Phone -> Download -> <some file>
370 elif uri_authority == 'com.android.providers.downloads.documents':
371 path = downloads = self._handle_downloads_documents(uri)
372
373 elif uri_authority == 'com.android.providers.media.documents':
374 file_name, selection, uri = self._handle_media_documents(uri)
375
376 # parse content:// scheme to path
377 if uri_scheme == 'content' and not downloads:
378 try:
379 path = self._parse_content(
380 uri=uri, projection=['_data'], selection=selection,
381 selection_args=file_name, sort_order=None
382 )
383 except JavaException: # handles array error for selection_args
384 path = self._parse_content(
385 uri=uri, projection=['_data'], selection=selection,
386 selection_args=[file_name], sort_order=None
387 )
388
389 # nothing to parse, file:// will return a proper path
390 elif uri_scheme == 'file':
391 path = uri.getPath()
392
393 return path
394
395 @staticmethod
396 def _parse_content(
397 uri, projection, selection, selection_args, sort_order,
398 index_all=False
399 ):
400 '''
401 Parser for ``content://`` URI returned by some Android resources.
402
403 .. versionadded:: 1.4.0
404 '''
405
406 result = None
407 resolver = mActivity.getContentResolver()
408 read = Intent.FLAG_GRANT_READ_URI_PERMISSION
409 write = Intent.FLAG_GRANT_READ_URI_PERMISSION
410 persist = Intent.FLAG_GRANT_READ_URI_PERMISSION
411
412 # grant permission for our activity
413 mActivity.grantUriPermission(
414 mActivity.getPackageName(),
415 uri,
416 read | write | persist
417 )
418
419 if not index_all:
420 cursor = resolver.query(
421 uri, projection, selection,
422 selection_args, sort_order
423 )
424
425 idx = cursor.getColumnIndex(projection[0])
426 if idx != -1 and cursor.moveToFirst():
427 result = cursor.getString(idx)
428 else:
429 result = []
430 cursor = resolver.query(
431 uri, projection, selection,
432 selection_args, sort_order
433 )
434 while cursor.moveToNext():
435 for idx in range(cursor.getColumnCount()):
436 result.append(cursor.getString(idx))
437 result = '/'.join(result)
438 return result
439
440 def _file_selection_dialog(self, **kwargs):
441 mode = kwargs.pop('mode', None)
442 if mode == 'open':
443 self._open_file(**kwargs)
444
445
446 def instance():
447 return AndroidFileChooser()