-
Notifications
You must be signed in to change notification settings - Fork 36
/
portalpy.py
2292 lines (1845 loc) · 99.2 KB
/
portalpy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" The portalpy module for working with the ArcGIS Online and Portal APIs."""
__version__ = '1.0'
import collections
import copy
import gzip
import httplib
import imghdr
import json
import logging
import mimetools
import mimetypes
import os
import re
import tempfile
import unicodedata
import urllib
import urllib2
import urlparse
from cStringIO import StringIO
_log = logging.getLogger(__name__)
class Portal(object):
""" An object representing a connection to a single portal (via URL).
.. note:: To instantiate a Portal object execute code like this:
PortalPy.Portal(portalUrl, user, password)
There are a few things you should know as you use the methods below.
Group IDs - Many of the group functions require a group id. This id is
different than the group's name or title. To determine
a group id, use the search_groups function using the title
to get the group id.
Time - Many of the methods return a time field. All time is
returned as millseconds since 1 January 1970. Python
expects time in seconds since 1 January 1970 so make sure
to divide times from PortalPy by 1000. See the example
a few lines down to see how to convert from PortalPy time
to Python time.
Example - converting time
.. code-block:: python
import time
.
.
.
group = portalAdmin.get_group('67e1761068b7453693a0c68c92a62e2e')
pythontime = time.ctime(group['created']/1000)
Example - list users in group
.. code-block:: python
portal = PortalPy.Portal(portalUrl, user, password)
resp = portal.get_group_members('67e1761068b7453693a0c68c92a62e2e')
for user in resp['users']:
print user
Example - create a group
.. code-block:: python
portal= PortalPy.Portal(portalUrl, user, password)
group_id = portalAdmin.create_group('my group', 'test tag', 'a group to share travel maps')
Example - delete a user named amy and assign her content to bob
.. code-block:: python
portal = PortalPy.Portal(portalUrl, user, password)
portal.delete_user('amy.user', True, 'bob.user')
"""
def __init__(self, url, username=None, password=None, key_file=None,
cert_file=None, expiration=60, referer=None, proxy_host=None,
proxy_port=None, connection=None, workdir=tempfile.gettempdir()):
""" The Portal constructor. Requires URL and optionally username/password."""
self.url = url
if url:
normalized_url = _normalize_url(self.url)
if not normalized_url[-1] == '/':
normalized_url += '/'
self.resturl = normalized_url + 'sharing/rest/'
self.hostname = _parse_hostname(url)
self.workdir = workdir
# Setup the instance members
self._basepostdata = { 'f': 'json' }
self._version = None
self._properties = None
self._logged_in_user = None
self._resources = None
self._languages = None
self._regions = None
self._is_pre_162 = False
self._is_pre_21 = False
# If a connection was passed in, use it, otherwise setup the
# connection (use all SSL until portal informs us otherwise)
if connection:
_log.debug('Using existing connection to: ' + \
_parse_hostname(connection.baseurl))
self.con = connection
if not connection:
_log.debug('Connecting to portal: ' + self.hostname)
self.con = _ArcGISConnection(self.resturl, username, password,
key_file, cert_file, expiration, True,
referer, proxy_host, proxy_port)
# Store the logged in user information. It's useful.
if self.is_logged_in():
self._logged_in_user = self.get_user(username)
self.get_version(True)
self.get_properties(True)
def add_group_users(self, user_names, group_id):
""" Adds users to the group specified.
.. note::
This method will only work if the user for the
Portal object is either an administrator for the entire
Portal or the owner of the group.
============ ======================================
**Argument** **Description**
------------ --------------------------------------
user_names required string, comma-separated users
------------ --------------------------------------
group_id required string, specifying group id
============ ======================================
:return:
A dictionary with a key of "not_added" which contains the users that were not
added to the group.
"""
if self._is_pre_21:
_log.warning('The auto_accept option is not supported in ' \
+ 'pre-2.0 portals')
return
user_names = _unpack(user_names, 'username')
postdata = self._postdata()
postdata['users'] = ','.join(user_names)
resp = self.con.post('community/groups/' + group_id + '/addUsers',
postdata)
return resp
def add_item(self, item_properties, data=None, thumbnail=None, metadata=None, owner=None, folder=None):
""" Adds content to a Portal.
.. note::
That content can be a file (such as a layer package, geoprocessing package,
map package) or it can be a URL (to an ArcGIS Server service, WMS service,
or an application).
If you are uploading a package or other file, provide a path or URL
to the file in the data argument.
From a technical perspective, none of the item properties below are required. However,
it is strongly recommended that title, type, typeKeywords, tags, snippet, and description
be provided.
============ ====================================================
**Argument** **Description**
------------ ----------------------------------------------------
item_properties required dictionary, see below for the keys and values
------------ ----------------------------------------------------
data optional string, either a path or URL to the data
------------ ----------------------------------------------------
thumbnail optional string, either a path or URL to an image
------------ ----------------------------------------------------
metadata optional string, either a path or URL to metadata.
------------ ----------------------------------------------------
owner optional string, defaults to logged in user.
------------ ----------------------------------------------------
folder optional string, content folder where placing item
============ ====================================================
================ ============================================================================
**Key** **Value**
---------------- ----------------------------------------------------------------------------
type optional string, indicates type of item. See URL 1 below for valid values.
---------------- ----------------------------------------------------------------------------
typeKeywords optinal string list. Lists all sub-types. See URL 1 for valid values.
---------------- ----------------------------------------------------------------------------
description optional string. Description of the item.
---------------- ----------------------------------------------------------------------------
title optional string. Name of the item.
---------------- ----------------------------------------------------------------------------
url optional string. URL to item that are based on URLs.
---------------- ----------------------------------------------------------------------------
tags optional string of comma-separated values. Used for searches on items.
---------------- ----------------------------------------------------------------------------
snippet optional string. Provides a very short summary of the what the item is.
---------------- ----------------------------------------------------------------------------
extent optional string with comma separated values for min x, min y, max x, max y.
---------------- ----------------------------------------------------------------------------
spatialReference optional string. Coordinate system that the item is in.
---------------- ----------------------------------------------------------------------------
accessInformation optional string. Information on the source of the content.
---------------- ----------------------------------------------------------------------------
licenseInfo optinal string, any license information or restrictions regarding the content.
---------------- ----------------------------------------------------------------------------
culture optional string. Locale, country and language information.
---------------- ----------------------------------------------------------------------------
access optional string. Valid values: private, shared, org, or public.
---------------- ----------------------------------------------------------------------------
commentsEnabled optional boolean. Default is true. Controls whether comments are allowed.
---------------- ----------------------------------------------------------------------------
culture optional string. Language and country information.
================ ============================================================================
URL 1: http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000ms000000
:return:
The item id of the uploaded item if successful, None if unsuccessful.
"""
# Postdata is a dictionary object whose keys and values will be sent via an HTTP Post.
postdata = self._postdata()
postdata.update(_unicode_to_ascii(item_properties))
# Build the files list (tuples)
files = []
if data:
if _is_http_url(data):
data = urllib.urlretrieve(data)[0]
files.append(('file', data, os.path.basename(data)))
if metadata:
if _is_http_url(metadata):
metadata = urllib.urlretrieve(metadata)[0]
files.append(('metadata', metadata, 'metadata.xml'))
if thumbnail:
if _is_http_url(thumbnail):
thumbnail = urllib.urlretrieve(thumbnail)[0]
file_ext = os.path.splitext(thumbnail)[1]
if not file_ext:
file_ext = imghdr.what(thumbnail)
if file_ext in ('gif', 'png', 'jpeg'):
new_thumbnail = thumbnail + '.' + file_ext
os.rename(thumbnail, new_thumbnail)
thumbnail = new_thumbnail
files.append(('thumbnail', thumbnail, os.path.basename(thumbnail)))
# If owner isn't specified, use the logged in user
if not owner:
owner = self.logged_in_user()['username']
# Setup the item path, including the folder, and post to it
path = 'content/users/' + owner
if folder:
path += '/' + folder
path += '/addItem'
resp = self.con.post(path, postdata, files)
if resp and resp.get('success'):
return resp['id']
def create_group_from_dict(self, group, thumbnail=None):
""" Creates a group and returns a group id if successful.
.. note::
Use create_group in most cases. This method is useful for taking a group
dict returned from another PortalPy call and copying it.
============ ======================================
**Argument** **Description**
------------ --------------------------------------
group dict object
------------ --------------------------------------
thumbnail url to image
============ ======================================
Example
.. code-block:: python
create_group({'title': 'Test', 'access':'public'})
"""
postdata = self._postdata()
postdata.update(_unicode_to_ascii(group))
# Build the files list (tuples)
files = []
if thumbnail:
if _is_http_url(thumbnail):
thumbnail = urllib.urlretrieve(thumbnail)[0]
file_ext = os.path.splitext(thumbnail)[1]
if not file_ext:
file_ext = imghdr.what(thumbnail)
if file_ext in ('gif', 'png', 'jpeg'):
new_thumbnail = thumbnail + '.' + file_ext
os.rename(thumbnail, new_thumbnail)
thumbnail = new_thumbnail
files.append(('thumbnail', thumbnail, os.path.basename(thumbnail)))
# Send the POST request, and return the id from the response
resp = self.con.post('community/createGroup', postdata, files)
if resp and resp.get('success'):
return resp['group']['id']
def create_group(self, title, tags, description=None,
snippet=None, access='public', thumbnail=None,
is_invitation_only=False, sort_field='avgRating',
sort_order='desc', is_view_only=False, ):
""" Creates a group and returns a group id if successful.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
title required string, name of the group
---------------- --------------------------------------------------------
tags required string, comma-delimited list of tags
---------------- --------------------------------------------------------
description optional string, describes group in detail
---------------- --------------------------------------------------------
snippet optional string, <250 characters summarizes group
---------------- --------------------------------------------------------
access optional string, can be private, public, or org
---------------- --------------------------------------------------------
thumbnail optional string, URL to group image
---------------- --------------------------------------------------------
isInvitationOnly optional boolean, defines whether users can join by request.
---------------- --------------------------------------------------------
sort_field optional string, specifies how shared items with the group are sorted.
---------------- --------------------------------------------------------
sort_order optional string, asc or desc for ascending or descending.
---------------- --------------------------------------------------------
is_view_only optional boolean, defines whether the group is searchable
================ ========================================================
:return:
a string that is a group id.
"""
return self.create_group_from_dict({'title' : title, 'tags' : tags,
'snippet' : snippet, 'access' : access,
'sortField' : sort_field, 'sortOrder' : sort_order,
'isViewOnly' : is_view_only,
'isinvitationOnly' : is_invitation_only}, thumbnail)
def delete_group(self, group_id):
""" Deletes a group.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
group_id string containing the id for the group to be deleted.
================ ========================================================
Returns
a boolean indicating whether it was successful.
"""
resp = self.con.post('community/groups/' + group_id + '/delete',
self._postdata())
if resp:
return resp.get('success')
def delete_item(self, item_id, folder=None, owner=None):
""" Deletes a single item from Portal.
.. note::
The delete item method requires the user to be logged in. Administrators
can delete any item in the Portal, but everyone else can only delete
their own items.
When called by an administrator on another user's items, the owner
of the item should be specified as an argument.
The folder in which the item resides must always be provided unless the
item is in the user's root folder. If it's in the root folder then the
folder argument can be omitted.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
item_id required string containing the id of the item to be deleted.
---------------- --------------------------------------------------------
owner optional string, the owner of the item, defaults to the logged in user.
---------------- --------------------------------------------------------
folder optonal string, the folder in which the item exists. Set to None for root.
================ ========================================================
Returns
a boolean indicating whether it was successful.
"""
if owner is None:
owner = self.con._username
if folder is None :
path = 'content/users/' + owner + '/items/' + item_id + '/delete'
else :
path = 'content/users/' + owner + '/' + folder + '/items/' + item_id + '/delete'
resp = self.con.post(path, self._postdata())
if resp:
return resp.get('success')
def delete_items(self, item_ids):
""" Deletes multiple items in Portal.
.. note::
The delete items method requires the user to be logged in. Administrators
can delete any item in the Portal, but everyone else can only delete
their own items.
This method takes a list of item ids.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
item_ids required list of strings containing the item ids to delete
---------------- --------------------------------------------------------
owner optional string, the owner of the item, defaults to the logged in user.
---------------- --------------------------------------------------------
folder optonal string, the folder in which the item exists. Set to None for root.
================ ========================================================
Returns
a list of dictionary objects that have itemId and success as the properties.
Example:
resp = portal.delete_items([item1, item2, item3])
for item in resp :
print item['itemId'] + ':' + str(item['success'])
"""
postdata = self._postdata()
postdata['items'] = ','.join(item_ids)
resp = self.con.post('content/users/' + self.con._username + '/deleteItems', postdata)
return resp['results']
def delete_user(self, username, reassign_to=None):
""" Deletes a user from the portal, optionally deleting or reassigning groups and items.
.. note::
You can not delete a user in Portal if that user owns groups or items. If you
specify someone in the reassign_to argument then items and groups will be
transferred to that user. If that argument is not set then the method
will fail if the user has items or groups that need to be reassigned.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
username required string, the name of the user
---------------- --------------------------------------------------------
reassign_to optional string, new owner of items and groups
================ ========================================================
:return:
a boolean indicating whether the operation succeeded or failed.
"""
if reassign_to :
self.reassign_user(username, reassign_to)
resp = self.con.post('community/users/' + username + '/delete',self._postdata())
if resp:
return resp.get('success')
else:
return False
def generate_token(self, username, password, expiration=60):
""" Generates and returns a new token, but doesn't re-login.
.. note::
This method is not needed when using the Portal class
to make calls into Portal. It's provided for the benefit
of making calls into Portal outside of the Portal class.
Portal uses a token-based authentication mechanism where
a user provides their credentials and a short-term token
is used for calls. Most calls made to the Portal REST API
require a token and this can be appended to those requests.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
username required string, name of the user
---------------- --------------------------------------------------------
password required password, name of the user
---------------- --------------------------------------------------------
expiration optional integer, number of minutes until the token expires
================ ========================================================
:return:
a string with the token
"""
return self.con.generate_token(username, password, expiration)
def get_group(self, group_id):
""" Returns group information for the specified group group_id.
Arguments
group_id : required string, indicating group.
:return:
a dictionary object with the group's information. The keys in
the dictionary object will often include:
================ ========================================================
**Key** **Value**
---------------- --------------------------------------------------------
title: the name of the group
---------------- --------------------------------------------------------
isInvitationOnly if set to true, users can't apply to join the group.
---------------- --------------------------------------------------------
owner: the owner username of the group
---------------- --------------------------------------------------------
description: explains the group
---------------- --------------------------------------------------------
snippet: a short summary of the group
---------------- --------------------------------------------------------
tags: user-defined tags that describe the group
---------------- --------------------------------------------------------
phone: contact information for group.
---------------- --------------------------------------------------------
thumbnail: File name relative to http://<community-url>/groups/<groupId>/info
---------------- --------------------------------------------------------
created: When group created, ms since 1 Jan 1970
---------------- --------------------------------------------------------
modified: When group last modified. ms since 1 Jan 1970
---------------- --------------------------------------------------------
access: Can be private, org, or public.
---------------- --------------------------------------------------------
userMembership: A dict with keys username and memberType.
---------------- --------------------------------------------------------
memberType: provides the calling user's access (owner, admin, member, none).
================ ========================================================
"""
return self.con.post('community/groups/' + group_id, self._postdata())
def get_group_thumbnail(self, group_id):
""" Returns the bytes that make up the thumbnail for the specified group group_id.
Arguments
group_id: required string, specifies the group's thumbnail
Returns
bytes that representt he image.
Example
.. code-block:: python
response = portal.get_group_thumbnail("67e1761068b7453693a0c68c92a62e2e")
f = open(filename, 'wb')
f.write(response)
"""
thumbnail_file = self.get_group(group_id).get('thumbnail')
if thumbnail_file:
thumbnail_url_path = 'community/groups/' + group_id + '/info/' + thumbnail_file
if thumbnail_url_path:
return self.con.get(thumbnail_url_path, try_json=False)
def get_group_members(self, group_id):
""" Returns members of the specified group.
Arguments
group_id: required string, specifies the group
Returns
a dictionary with keys: owner, admins, and users.
================ ========================================================
**Key** **Value**
---------------- --------------------------------------------------------
owner string value, the group's owner
---------------- --------------------------------------------------------
admins list of strings, typically this is the same as the owner.
---------------- --------------------------------------------------------
users list of strings, the members of the group
================ ========================================================
Example (to print users in a group)
.. code-block:: python
response = portal.get_group_members("67e1761068b7453693a0c68c92a62e2e")
for user in response['users'] :
print user
"""
return self.con.post('community/groups/' + group_id + '/users',
self._postdata())
def get_org_users(self, max_users=1000):
""" Returns all users within the portal organization.
Arguments
max_users : optional int, the maximum number of users to return.
:return:
a list of dicts. Each dict has the following keys:
================ ========================================================
**Key** **Value**
---------------- --------------------------------------------------------
username : string
---------------- --------------------------------------------------------
storageUsage: int
---------------- --------------------------------------------------------
storageQuota: int
---------------- --------------------------------------------------------
description: string
---------------- --------------------------------------------------------
tags: list of strings
---------------- --------------------------------------------------------
region: string
---------------- --------------------------------------------------------
created: int, when account created, ms since 1 Jan 1970
---------------- --------------------------------------------------------
modified: int, when account last modified, ms since 1 Jan 1970
---------------- --------------------------------------------------------
email: string
---------------- --------------------------------------------------------
culture: string
---------------- --------------------------------------------------------
orgId: string
---------------- --------------------------------------------------------
preferredView: string
---------------- --------------------------------------------------------
groups: list of strings
---------------- --------------------------------------------------------
role: string (org_user, org_publisher, org_admin)
---------------- --------------------------------------------------------
fullName: string
---------------- --------------------------------------------------------
thumbnail: string
---------------- --------------------------------------------------------
idpUsername: string
================ ========================================================
Example (print all usernames in portal):
.. code-block:: python
resp = portalAdmin.get_org_users()
for user in resp:
print user['username']
"""
# Execute the search and get back the results
count = 0
resp = self._org_users_page(1, min(max_users, 100))
resp_users = resp.get('users')
results = resp_users
count += int(resp['num'])
nextstart = int(resp['nextStart'])
while count < max_users and nextstart > 0:
resp = self._org_users_page(nextstart, min(max_users - count, 100))
resp_users = resp.get('users')
results.extend(resp_users)
count += int(resp['num'])
nextstart = int(resp['nextStart'])
return results
def get_properties(self, force=False):
""" Returns the portal properties (using cache unless force=True). """
# If we've never retrieved the properties before, or the caller is
# forcing a check of the server, then check the server
if not self._properties or force:
path = 'accounts/self' if self._is_pre_162 else 'portals/self'
resp = self.con.post(path, self._postdata(), ssl=True)
if resp:
self._properties = resp
self.con.all_ssl = self.is_all_ssl()
# Return a defensive copy
return copy.deepcopy(self._properties)
def get_user(self, username):
""" Returns the user information for the specified username.
Arguments
username required string, the username whose information you want.
:return:
None if the user is not found and returns a dictionary object if the user is found
the dictionary has the following keys:
================ ========================================================
**Key** **Value**
---------------- --------------------------------------------------------
access string
---------------- --------------------------------------------------------
created time (int)
---------------- --------------------------------------------------------
culture string, two-letter language code ('en')
---------------- --------------------------------------------------------
description string
---------------- --------------------------------------------------------
email string
---------------- --------------------------------------------------------
fullName string
---------------- --------------------------------------------------------
idpUsername string, name of the user in the enterprise system
---------------- --------------------------------------------------------
groups list of dictionaries. For dictionary keys, see get_group doc.
---------------- --------------------------------------------------------
modified time (int)
---------------- --------------------------------------------------------
orgId string, the organization id
---------------- --------------------------------------------------------
preferredView string, value is either Web, GIS, or null
---------------- --------------------------------------------------------
region string, None or two letter country code
---------------- --------------------------------------------------------
role string, value is either org_user, org_publisher, org_admin
---------------- --------------------------------------------------------
storageUsage int
---------------- --------------------------------------------------------
storageQuota int
---------------- --------------------------------------------------------
tags list of strings
---------------- --------------------------------------------------------
thumbnail string, name of file
---------------- --------------------------------------------------------
username string, name of user
================ ========================================================
"""
return self.con.post('community/users/' + username, self._postdata())
def invite_group_users(self, user_names, group_id,
role='group_member', expiration=10080):
""" Invites users to a group.
.. note::
A user who is invited to a group will see a list of invitations
in the "Groups" tab of portal listing invitations. The user
can either accept or reject the invitation.
Requires
The user executing the command must be group owner
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
user_names: a required string list of users to invite
---------------- --------------------------------------------------------
group_id : required string, specifies the group you are inviting users to.
---------------- --------------------------------------------------------
role: an optional string, either group_member or group_admin
---------------- --------------------------------------------------------
expiration: an optional int, specifies how long the invitation is valid for in minutes.
================ ========================================================
:return:
a boolean that indicates whether the call succeeded.
"""
user_names = _unpack(user_names, 'username')
# Send out the invitations
postdata = self._postdata()
postdata['users'] = ','.join(user_names)
postdata['role'] = role
postdata['expiration'] = expiration
resp = self.con.post('community/groups/' + group_id + '/invite',
postdata)
if resp:
return resp.get('success')
def is_logged_in(self):
""" Returns true if logged into the portal. """
return self.con.is_logged_in()
def is_all_ssl(self):
""" Returns true if this portal requires SSL. """
# If properties aren't set yet, return true (assume SSL until the
# properties tell us otherwise)
if not self._properties:
return True
# If access property doesnt exist, will correctly return false
return self._properties.get('allSSL')
def is_multitenant(self):
""" Returns true if this portal is multitenant. """
return self._properties['portalMode'] == 'multitenant'
def is_arcgisonline(self):
""" Returns true if this portal is ArcGIS Online. """
return self._properties['portalName'] == 'ArcGIS Online' \
and self.is_multitenant()
def is_subscription(self):
""" Returns true if this portal is an ArcGIS Online subscription. """
return bool(self._properties.get('urlKey'))
def is_org(self):
""" Returns true if this portal is an organization. """
return bool(self._properties.get('id'))
def leave_group(self, group_id):
""" Removes the logged in user from the specified group.
Requires:
User must be logged in.
Arguments:
group_id: required string, specifies the group id
:return:
a boolean indicating whether the operation was successful.
"""
resp = self.con.post('community/groups/' + group_id + '/leave',
self._postdata())
if resp:
return resp.get('success')
def login(self, username, password, expiration=60):
""" Logs into the portal using username/password.
.. note::
You can log into a portal when you construct a portal
object or you can login later. This function is
for the situation when you need to log in later.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
username required string
---------------- --------------------------------------------------------
password required string
---------------- --------------------------------------------------------
expiration optional int, how long the token generated should last.
================ ========================================================
:return:
a string, the token
"""
newtoken = self.con.login(username, password, expiration)
if newtoken:
self._logged_in_user = self.get_user(username)
return newtoken
def logout(self):
""" Logs out of the portal.
.. note::
The portal will forget any existing tokens it was using, all
subsequent portal calls will be anonymous until another login
call occurs.
:return:
No return value.
"""
self.con.logout()
def logged_in_user(self):
""" Returns information about the logged in user.
:return:
a dict with the following keys:
================ ========================================================
**Key** **Value**
---------------- --------------------------------------------------------
username string
---------------- --------------------------------------------------------
storageUsage int
---------------- --------------------------------------------------------
description string
---------------- --------------------------------------------------------
tags comma-separated string
---------------- --------------------------------------------------------
created int, when group created (ms since 1 Jan 1970)
---------------- --------------------------------------------------------
modified int, when group last modified (ms since 1 Jan 1970)
---------------- --------------------------------------------------------
fullName string
---------------- --------------------------------------------------------
email string
---------------- --------------------------------------------------------
idpUsername string, name of the user in their identity provider
================ ========================================================
"""
if self._logged_in_user:
# Return a defensive copy
return copy.deepcopy(self._logged_in_user)
return None
def reassign_user(self, username, target_username):
""" Reassigns all of a user's items and groups to another user.
Items are transferred to the target user into a folder named
<user>_<folder> where user corresponds to the user whose items were
moved and folder corresponds to the folder that was moved.
.. note::
This method must be executed as an administrator. This method also
can not be undone. The changes are immediately made and permanent.
================ ========================================================
**Argument** **Description**
---------------- --------------------------------------------------------
username required string, user who will have items/groups transferred
---------------- --------------------------------------------------------
target_username required string, user who will own items/groups after this.
================ ========================================================
:return:
a boolean indicating success
"""
postdata = self._postdata()
postdata['targetUsername'] = target_username
resp = self.con.post('community/users/' + username + '/reassign', postdata)
if resp:
return resp.get('success')
def reassign_group(self, group_id, target_owner):
""" Reassigns a group to another owner.