-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathviews.py
executable file
·5096 lines (4537 loc) · 185 KB
/
views.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2020 University of Dundee & Open Microscopy Environment.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" A view functions is simply a Python function that takes a Web request and
returns a Web response. This response can be the HTML contents of a Web page,
or a redirect, or the 404 and 500 error, or an XML document, or an image...
or anything."""
import copy
import csv
import os
import datetime
from io import StringIO
import Ice
from Ice import Exception as IceException
import logging
import traceback
import json
import re
import sys
import warnings
from collections import defaultdict
from django.utils.html import escape
from django.utils.http import url_has_allowed_host_and_scheme
from time import time
from omeroweb.version import omeroweb_buildyear as build_year
from omeroweb.version import omeroweb_version as omero_version
import omero
import omero.scripts
from omero.rtypes import wrap, unwrap, rlong, rlist
from omero.gateway.utils import toBoolean
from django.conf import settings
from django.template import loader as template_loader
from django.http import (
Http404,
HttpResponse,
HttpResponseRedirect,
JsonResponse,
HttpResponseForbidden,
)
from django.http import HttpResponseServerError, HttpResponseBadRequest
from django.utils.http import urlencode
from django.urls import reverse, NoReverseMatch
from django.utils.encoding import smart_str
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from django.shortcuts import render
from omeroweb.webclient.webclient_utils import _formatReport, _purgeCallback
from .forms import GlobalSearchForm, ContainerForm
from .forms import ShareForm
from .forms import ContainerNameForm, ContainerDescriptionForm
from .forms import CommentAnnotationForm, TagsAnnotationForm
from .forms import MetadataFilterForm, MetadataDetectorForm
from .forms import MetadataChannelForm, MetadataEnvironmentForm
from .forms import MetadataObjectiveForm, MetadataObjectiveSettingsForm
from .forms import MetadataStageLabelForm, MetadataLightSourceForm
from .forms import MetadataDichroicForm, MetadataMicroscopeForm
from .forms import FilesAnnotationForm, WellIndexForm, NewTagsAnnotationFormSet
from .controller.container import BaseContainer
from .controller.history import BaseCalendar
from .controller.search import BaseSearch
from .controller.share import BaseShare
from omeroweb.webadmin.forms import LoginForm
from omeroweb.webgateway import views as webgateway_views
from omeroweb.webgateway.marshal import graphResponseMarshal
from omeroweb.webgateway.util import get_longs as webgateway_get_longs
from omeroweb.feedback.views import handlerInternalError
from omeroweb.webclient.decorators import login_required
from omeroweb.webclient.decorators import render_response
from omeroweb.webclient.show import (
Show,
IncorrectMenuError,
paths_to_object,
paths_to_tag,
)
from omeroweb.decorators import (
ConnCleaningHttpResponse,
parse_url,
TableClosingHttpResponse,
)
from omeroweb.webgateway.util import getIntOrDefault
from omero.model import (
AnnotationAnnotationLinkI,
DatasetI,
DatasetImageLinkI,
ExperimenterI,
ImageI,
OriginalFileI,
PlateI,
ProjectI,
ProjectDatasetLinkI,
ScreenI,
ScreenPlateLinkI,
TagAnnotationI,
)
from omero import ApiUsageException, ServerError, CmdError
from omeroweb.webgateway.views import LoginView
from . import tree
logger = logging.getLogger(__name__)
logger.info("INIT '%s'" % os.getpid())
# We want to allow a higher default limit for annotations so we can load
# all the annotations expected for a PAGE of images
ANNOTATIONS_LIMIT = settings.PAGE * 100
def get_long_or_default(request, name, default):
"""
Retrieves a parameter from the request. If the parameter is not present
the default is returned
This does not catch exceptions as it makes sense to throw exceptions if
the arguments provided do not pass basic type validation
"""
val = None
val_raw = request.GET.get(name, default)
if val_raw is not None:
val = int(val_raw)
return val
def get_list(request, name):
val = request.GET.getlist(name)
return [i for i in val if i != ""]
def get_longs(request, name):
warnings.warn(
"Deprecated. Use omeroweb.webgateway.util.get_longs()", DeprecationWarning
)
return webgateway_get_longs(request, name)
def get_bool_or_default(request, name, default):
"""
Retrieves a parameter from the request. If the parameter is not present
the default is returned
This does not catch exceptions as it makes sense to throw exceptions if
the arguments provided do not pass basic type validation
"""
return toBoolean(request.GET.get(name, default))
def validate_redirect_url(url):
"""
Returns a URL is safe to redirect to.
If url is a different host, not in settings.REDIRECT_ALLOWED_HOSTS
we return webclient index URL.
"""
if not url_has_allowed_host_and_scheme(
url, allowed_hosts=settings.REDIRECT_ALLOWED_HOSTS
):
url = reverse("webindex")
return url
##############################################################################
# custom index page
@never_cache
@render_response()
def custom_index(request, conn=None, **kwargs):
context = {"version": omero_version, "build_year": build_year}
if settings.INDEX_TEMPLATE is not None:
try:
template_loader.get_template(settings.INDEX_TEMPLATE)
context["template"] = settings.INDEX_TEMPLATE
except Exception:
context["template"] = "webclient/index.html"
context["error"] = traceback.format_exception(*sys.exc_info())[-1]
else:
context["template"] = "webclient/index.html"
return context
##############################################################################
# views
class WebclientLoginView(LoginView):
"""
Webclient Login - Customises the superclass LoginView
for webclient. Also can be used by other Apps to log in to OMERO. Uses
the 'server' id from request to lookup the server-id (index), host and
port from settings. E.g. "localhost", 4064. Stores these details, along
with username, password etc in the request.session. Resets other data
parameters in the request.session. Tries to get connection to OMERO and
if this works, then we are redirected to the 'index' page or url
specified in REQUEST. If we can't connect, the login page is returned
with appropriate error messages.
"""
template = "webclient/login.html"
useragent = "OMERO.web"
def get(self, request):
"""
GET simply returns the login page
"""
return self.handle_not_logged_in(request)
def handle_logged_in(self, request, conn, connector):
"""
We override this to provide webclient-specific functionality
such as cleaning up any previous sessions (if user didn't logout)
and redirect to specified url or webclient index page.
"""
# webclient has various state that needs cleaning up...
# if 'active_group' remains in session from previous
# login, check it's valid for this user
# NB: we do this for public users in @login_required.get_connection()
if request.session.get("active_group"):
if (
request.session.get("active_group")
not in conn.getEventContext().memberOfGroups
):
del request.session["active_group"]
if request.session.get("user_id"):
# always want to revert to logged-in user
del request.session["user_id"]
if request.session.get("server_settings"):
# always clean when logging in
del request.session["server_settings"]
# do we ned to display server version ?
# server_version = conn.getServerVersion()
if request.POST.get("noredirect"):
return HttpResponse("OK")
url = request.GET.get("url")
if url is None or len(url) == 0:
try:
url = parse_url(settings.LOGIN_REDIRECT)
except Exception:
url = reverse("webindex")
else:
url = validate_redirect_url(url)
return HttpResponseRedirect(url)
def handle_not_logged_in(self, request, error=None, form=None):
"""
Returns a response for failed login.
Reason for failure may be due to server 'error' or because
of form validation errors.
@param request: http request
@param error: Error message
@param form: Instance of Login Form, populated with data
"""
if form is None:
server_id = request.GET.get("server", request.POST.get("server"))
if server_id is not None:
initial = {"server": str(server_id)}
form = LoginForm(initial=initial)
else:
form = LoginForm()
context = {
"version": omero_version,
"build_year": build_year,
"error": error,
"form": form,
}
url = request.GET.get("url")
if url is not None and len(url) != 0:
context["url"] = urlencode({"url": url})
if hasattr(settings, "LOGIN_LOGO"):
context["LOGIN_LOGO"] = settings.LOGIN_LOGO
if settings.PUBLIC_ENABLED:
redirect = reverse("webindex")
if settings.PUBLIC_URL_FILTER.search(redirect):
context["public_enabled"] = True
context["public_login_redirect"] = redirect
if settings.SHOW_FORGOT_PASSWORD:
context["show_forgot_password"] = True
context["show_download_links"] = settings.SHOW_CLIENT_DOWNLOADS
if settings.SHOW_CLIENT_DOWNLOADS:
ver = re.match(
(
r"(?P<major>\d+)\."
r"(?P<minor>\d+)\."
r"(?P<patch>\d+\.?)?"
r"(?P<dev>(dev|a|b|rc)\d+)?.*"
),
omero_version,
)
client_download_tag_re = "^v%s\\.%s\\.[^-]+$" % (
ver.group("major"),
ver.group("minor"),
)
context["client_download_tag_re"] = client_download_tag_re
context["client_download_repo"] = settings.CLIENT_DOWNLOAD_GITHUB_REPO
return render(request, self.template, context)
@login_required(ignore_login_fail=True)
def keepalive_ping(request, conn=None, **kwargs):
"""Keeps the OMERO session alive by pinging the server"""
# login_required handles ping, timeout etc, so we don't need to do
# anything else
return HttpResponse("OK", content_type="text/plain")
@login_required()
def change_active_group(request, conn=None, url=None, **kwargs):
"""
Simply changes the request.session['active_group'] which is then used by
the @login_required decorator to configure conn for any group-based
queries.
Finally this redirects to the 'url'.
"""
switch_active_group(request)
# avoid recursive calls
if url is None or url.startswith(reverse("change_active_group")):
url = reverse("webindex")
url = validate_redirect_url(url)
return HttpResponseRedirect(url)
def switch_active_group(request, active_group=None):
"""
Simply changes the request.session['active_group'] which is then used by
the @login_required decorator to configure conn for any group-based
queries.
"""
if active_group is None:
active_group = get_long_or_default(request, "active_group", None)
if active_group is None:
return
active_group = int(active_group)
if (
"active_group" not in request.session
or active_group != request.session["active_group"]
):
request.session.modified = True
request.session["active_group"] = active_group
def fake_experimenter(request, default_name="All members"):
"""
Marshal faked experimenter when id is -1
Load omero.client.ui.menu.dropdown.everyone.label as username
"""
label = (
request.session.get("server_settings")
.get("ui", {})
.get("menu", {})
.get("dropdown", {})
.get("everyone", {})
.get("label", default_name)
)
return {
"id": -1,
"omeName": label,
"firstName": label,
"lastName": "",
}
@login_required(login_redirect="webindex")
def logout(request, conn=None, **kwargs):
"""
Logout of the session and redirects to the homepage (will redirect to
login first)
"""
if request.method == "POST":
try:
try:
conn.close()
except Exception:
logger.error("Exception during logout.", exc_info=True)
finally:
request.session.flush()
return HttpResponseRedirect(reverse(settings.LOGIN_VIEW))
else:
context = {"url": reverse("weblogout"), "submit": "Do you want to log out?"}
template = "webgateway/base/includes/post_form.html"
return render(request, template, context)
###########################################################################
def _load_template(request, menu, conn=None, url=None, **kwargs):
"""
This view handles most of the top-level pages, as specified by 'menu' E.g.
userdata, usertags, history, search etc.
Query string 'path' that specifies an object to display in the data tree
is parsed.
We also prepare the list of users in the current group, for the
switch-user form. Change-group form is also prepared.
"""
request.session.modified = True
template = kwargs.get("template", None)
if template is None:
if menu == "userdata":
template = "webclient/data/containers.html"
elif menu == "usertags":
template = "webclient/data/containers.html"
else:
# E.g. search/search.html
template = "webclient/%s/%s.html" % (menu, menu)
# tree support
show = kwargs.get("show", Show(conn, request, menu))
# Constructor does no loading. Show.first_selected must be called first
# in order to set up our initial state correctly.
try:
first_sel = show.first_selected
except IncorrectMenuError as e:
return HttpResponseRedirect(e.uri)
# We get the owner of the top level object, E.g. Project
# Actual api_paths_to_object() is retrieved by jsTree once loaded
initially_open_owner = show.initially_open_owner
# If we failed to find 'show'...
if request.GET.get("show", None) is not None and first_sel is None:
# and we're logged in as PUBLIC user...
if (
settings.PUBLIC_ENABLED
and settings.PUBLIC_USER == conn.getUser().getOmeName()
):
# this is likely a regular user who needs to log in as themselves.
# Login then redirect to current url
return HttpResponseRedirect("%s?url=%s" % (reverse("weblogin"), url))
# need to be sure that tree will be correct omero.group
if first_sel is not None:
group_id = first_sel.details.group.id.val
if conn.isValidGroup(group_id):
switch_active_group(request, group_id)
else:
first_sel = None
# search support
init = {}
global_search_form = GlobalSearchForm(data=request.GET.copy())
if menu == "search":
if global_search_form.is_valid():
init["query"] = global_search_form.cleaned_data["search_query"]
# get url without request string - used to refresh page after switch
# user/group etc
url = kwargs.get("load_template_url", None)
if url is None:
url = reverse(viewname="load_template", args=[menu])
# validate experimenter is in the active group
active_group = request.session.get("active_group") or conn.getEventContext().groupId
# prepare members of group...
leaders, members = conn.getObject("ExperimenterGroup", active_group).groupSummary()
userIds = [u.id for u in leaders]
userIds.extend([u.id for u in members])
# check any change in experimenter...
user_id = request.GET.get("experimenter")
if initially_open_owner is not None:
if request.session.get("user_id", None) != -1:
# if we're not already showing 'All Members'...
user_id = initially_open_owner
try:
user_id = int(user_id)
except Exception:
user_id = None
# check if user_id is in a currnt group
if user_id is not None:
if (
user_id
not in (
set(map(lambda x: x.id, leaders)) | set(map(lambda x: x.id, members))
)
and user_id != -1
):
# All users in group is allowed
user_id = None
if user_id is None:
# ... or check that current user is valid in active group
user_id = request.session.get("user_id", None)
if user_id is None or int(user_id) not in userIds:
if user_id != -1: # All users in group is allowed
user_id = conn.getEventContext().userId
request.session["user_id"] = user_id
myGroups = list(conn.getGroupsMemberOf())
myGroups.sort(key=lambda x: x.getName().lower())
groups = myGroups
new_container_form = ContainerForm()
# colleagues required for search.html page only.
myColleagues = {}
if menu == "search":
for g in groups:
g.loadLeadersAndMembers()
for c in g.leaders + g.colleagues:
myColleagues[c.id] = c
myColleagues = list(myColleagues.values())
myColleagues.sort(key=lambda x: x.getLastName().lower())
context = {
"menu": menu,
"init": init,
"myGroups": myGroups,
"new_container_form": new_container_form,
"global_search_form": global_search_form,
}
context["groups"] = groups
context["myColleagues"] = myColleagues
context["active_group"] = conn.getObject("ExperimenterGroup", int(active_group))
context["active_user"] = conn.getObject("Experimenter", int(user_id))
context["initially_select"] = show.initially_select
context["initially_open"] = show.initially_open
context["isLeader"] = conn.isLeader()
context["current_url"] = url
context["page_size"] = settings.PAGE
context["template"] = template
context["thumbnails_batch"] = settings.THUMBNAILS_BATCH
context["current_admin_privileges"] = conn.getCurrentAdminPrivileges()
context["leader_of_groups"] = conn.getEventContext().leaderOfGroups
context["member_of_groups"] = conn.getEventContext().memberOfGroups
context["search_default_user"] = settings.SEARCH_DEFAULT_USER
context["search_default_group"] = settings.SEARCH_DEFAULT_GROUP
return context
@login_required()
@render_response()
def load_template(request, menu, conn=None, url=None, **kwargs):
return _load_template(request=request, menu=menu, conn=conn, url=url, **kwargs)
@login_required()
@render_response()
def group_user_content(request, url=None, conn=None, **kwargs):
"""
Loads html content of the Groups/Users drop-down menu on main webclient
pages.
Url should be supplied in request, as target for redirect after switching
group.
"""
myGroups = list(conn.getGroupsMemberOf())
myGroups.sort(key=lambda x: x.getName().lower())
if conn.isAdmin(): # Admin can see all groups
system_groups = [
conn.getAdminService().getSecurityRoles().userGroupId,
conn.getAdminService().getSecurityRoles().guestGroupId,
]
groups = conn.getObjects("ExperimenterGroup", opts={"load_experimenters": True})
groups = [g for g in groups if g.getId() not in system_groups]
groups.sort(key=lambda x: x.getName().lower())
else:
groups = myGroups
for g in groups:
g.loadLeadersAndMembers() # load leaders / members
context = {
"template": "webclient/base/includes/group_user_content.html",
"current_url": url,
"groups": groups,
"myGroups": myGroups,
}
return context
@login_required()
def api_group_list(request, conn=None, **kwargs):
# Get parameters
try:
page = get_long_or_default(request, "page", 1)
limit = get_long_or_default(request, "limit", settings.PAGE)
member_id = get_long_or_default(request, "member", -1)
except ValueError:
return HttpResponseBadRequest("Invalid parameter value")
try:
# Get the groups
groups = tree.marshal_groups(
conn=conn, member_id=member_id, page=page, limit=limit
)
except ApiUsageException as e:
return HttpResponseBadRequest(e.serverStackTrace)
except ServerError as e:
return HttpResponseServerError(e.serverStackTrace)
except IceException as e:
return HttpResponseServerError(e.message)
return JsonResponse({"groups": groups})
@login_required()
def api_experimenter_detail(request, experimenter_id, conn=None, **kwargs):
# Validate parameter
try:
experimenter_id = int(experimenter_id)
except ValueError:
return HttpResponseBadRequest("Invalid experimenter id")
try:
# Get the experimenter
if experimenter_id < 0:
experimenter = fake_experimenter(request)
else:
# Get the experimenter
experimenter = tree.marshal_experimenter(
conn=conn, experimenter_id=experimenter_id
)
if experimenter is None:
raise Http404("No Experimenter found with ID %s" % experimenter_id)
return JsonResponse({"experimenter": experimenter})
except ApiUsageException as e:
return HttpResponseBadRequest(e.serverStackTrace)
except ServerError as e:
return HttpResponseServerError(e.serverStackTrace)
except IceException as e:
return HttpResponseServerError(e.message)
@login_required()
def api_container_list(request, conn=None, **kwargs):
# Get parameters
try:
page = get_long_or_default(request, "page", 1)
limit = get_long_or_default(request, "limit", settings.PAGE)
group_id = get_long_or_default(request, "group", -1)
experimenter_id = get_long_or_default(request, "id", -1)
except ValueError:
return HttpResponseBadRequest("Invalid parameter value")
# While this interface does support paging, it does so in a
# very odd way. The results per page is enforced per query so this
# will actually get the limit for projects, datasets (without
# parents), screens and plates (without parents). This is fine for
# the first page, but the second page may not be what is expected.
if not conn.isValidGroup(group_id):
return HttpResponseForbidden("Not a member of Group: %s" % group_id)
r = dict()
try:
# Get the projects
r["projects"] = tree.marshal_projects(
conn=conn,
group_id=group_id,
experimenter_id=experimenter_id,
page=page,
limit=limit,
)
# Get the orphaned datasets (without project parents)
r["datasets"] = tree.marshal_datasets(
conn=conn,
orphaned=True,
group_id=group_id,
experimenter_id=experimenter_id,
page=page,
limit=limit,
)
# Get the screens for the current user
r["screens"] = tree.marshal_screens(
conn=conn,
group_id=group_id,
experimenter_id=experimenter_id,
page=page,
limit=limit,
)
# Get the orphaned plates (without project parents)
r["plates"] = tree.marshal_plates(
conn=conn,
orphaned=True,
group_id=group_id,
experimenter_id=experimenter_id,
page=page,
limit=limit,
)
# Get the orphaned images container
try:
orph_t = request.session["server_settings"]["ui"]["tree"]["orphans"]
except Exception:
orph_t = {"enabled": True}
if (
conn.isAdmin()
or conn.isLeader(gid=request.session.get("active_group"))
or experimenter_id == conn.getUserId()
or orph_t.get("enabled", True)
):
orphaned = tree.marshal_orphaned(
conn=conn,
group_id=group_id,
experimenter_id=experimenter_id,
page=page,
limit=limit,
)
orphaned["name"] = orph_t.get("name", "Orphaned Images")
r["orphaned"] = orphaned
except ApiUsageException as e:
return HttpResponseBadRequest(e.serverStackTrace)
except ServerError as e:
return HttpResponseServerError(e.serverStackTrace)
except IceException as e:
return HttpResponseServerError(e.message)
return JsonResponse(r)
@login_required()
def api_dataset_list(request, conn=None, **kwargs):
# Get parameters
try:
page = get_long_or_default(request, "page", 1)
limit = get_long_or_default(request, "limit", settings.PAGE)
group_id = get_long_or_default(request, "group", -1)
project_id = get_long_or_default(request, "id", None)
except ValueError:
return HttpResponseBadRequest("Invalid parameter value")
if not conn.isValidGroup(group_id):
return HttpResponseForbidden("Not a member of Group: %s" % group_id)
try:
# Get the datasets
datasets = tree.marshal_datasets(
conn=conn, project_id=project_id, group_id=group_id, page=page, limit=limit
)
except ApiUsageException as e:
return HttpResponseBadRequest(e.serverStackTrace)
except ServerError as e:
return HttpResponseServerError(e.serverStackTrace)
except IceException as e:
return HttpResponseServerError(e.message)
return JsonResponse({"datasets": datasets})
@login_required()
def api_image_list(request, conn=None, **kwargs):
"""Get a list of images
Specifiying dataset_id will return only images in that dataset
Specifying experimenter_id will return orpahned images for that
user
The orphaned images will include images which belong to the user
but are not in any dataset belonging to the user
Currently specifying both, experimenter_id will be ignored
"""
# Get parameters
try:
page = get_long_or_default(request, "page", 1)
limit = get_long_or_default(request, "limit", settings.PAGE)
group_id = get_long_or_default(request, "group", -1)
dataset_id = get_long_or_default(request, "id", None)
orphaned = get_bool_or_default(request, "orphaned", False)
load_pixels = get_bool_or_default(request, "sizeXYZ", False)
thumb_version = get_bool_or_default(request, "thumbVersion", False)
date = get_bool_or_default(request, "date", False)
experimenter_id = get_long_or_default(request, "experimenter_id", -1)
except ValueError:
return HttpResponseBadRequest("Invalid parameter value")
if not conn.isValidGroup(group_id):
return HttpResponseForbidden("Not a member of Group: %s" % group_id)
# Share ID is in kwargs from api/share_images/<id>/ which will create
# a share connection in @login_required.
# We don't support ?share_id in query string since this would allow a
# share connection to be created for ALL urls, instead of just this one.
share_id = "share_id" in kwargs and int(kwargs["share_id"]) or None
try:
# Get the images
images = tree.marshal_images(
conn=conn,
orphaned=orphaned,
experimenter_id=experimenter_id,
dataset_id=dataset_id,
share_id=share_id,
load_pixels=load_pixels,
group_id=group_id,
page=page,
date=date,
thumb_version=thumb_version,
limit=limit,
)
except ApiUsageException as e:
return HttpResponseBadRequest(e.serverStackTrace)
except ServerError as e:
return HttpResponseServerError(e.serverStackTrace)
except IceException as e:
return HttpResponseServerError(e.message)
return JsonResponse({"images": images})
@login_required()
def api_plate_list(request, conn=None, **kwargs):
# Get parameters
try:
page = get_long_or_default(request, "page", 1)
limit = get_long_or_default(request, "limit", settings.PAGE)
group_id = get_long_or_default(request, "group", -1)
screen_id = get_long_or_default(request, "id", None)
except ValueError:
return HttpResponseBadRequest("Invalid parameter value")
if not conn.isValidGroup(group_id):
return HttpResponseForbidden("Not a member of Group: %s" % group_id)
try:
# Get the plates
plates = tree.marshal_plates(
conn=conn, screen_id=screen_id, group_id=group_id, page=page, limit=limit
)
except ApiUsageException as e:
return HttpResponseBadRequest(e.serverStackTrace)
except ServerError as e:
return HttpResponseServerError(e.serverStackTrace)
except IceException as e:
return HttpResponseServerError(e.message)
return JsonResponse({"plates": plates})
@login_required()
def api_plate_acquisition_list(request, conn=None, **kwargs):
# Get parameters
try:
page = get_long_or_default(request, "page", 1)
limit = get_long_or_default(request, "limit", settings.PAGE)
plate_id = get_long_or_default(request, "id", None)
except ValueError:
return HttpResponseBadRequest("Invalid parameter value")
# Orphaned PlateAcquisitions are not possible so querying without a
# plate is an error
if plate_id is None:
return HttpResponseBadRequest("id (plate) must be specified")
try:
# Get the plate acquisitions
plate_acquisitions = tree.marshal_plate_acquisitions(
conn=conn, plate_id=plate_id, page=page, limit=limit
)
except ApiUsageException as e:
return HttpResponseBadRequest(e.serverStackTrace)
except ServerError as e:
return HttpResponseServerError(e.serverStackTrace)
except IceException as e:
return HttpResponseServerError(e.message)
return JsonResponse({"acquisitions": plate_acquisitions})
def get_object_links(conn, parent_type, parent_id, child_type, child_ids):
"""This is just used internally by api_link DELETE below"""
if parent_type == "orphaned":
return None
link_type = None
if parent_type == "experimenter":
if child_type in ["dataset", "plate", "tag"]:
# This will be a requested link if a dataset or plate is
# moved from the de facto orphaned datasets/plates, it isn't
# an error, but no link actually needs removing
return None
elif parent_type == "project":
if child_type == "dataset":
link_type = "ProjectDatasetLink"
elif parent_type == "dataset":
if child_type == "image":
link_type = "DatasetImageLink"
elif parent_type == "screen":
if child_type == "plate":
link_type = "ScreenPlateLink"
elif parent_type == "tagset":
if child_type == "tag":
link_type = "AnnotationAnnotationLink"
if not link_type:
raise Http404("json data needs 'parent_type' and 'child_type'")
params = omero.sys.ParametersI()
params.addIds(child_ids)
qs = conn.getQueryService()
# Need to fetch child and parent, otherwise
# AnnotationAnnotationLink is not loaded
q = (
"""
from %s olink join fetch olink.child join fetch olink.parent
where olink.child.id in (:ids)
"""
% link_type
)
if parent_id:
params.add("pid", rlong(parent_id))
q += " and olink.parent.id = :pid"
res = qs.findAllByQuery(q, params, conn.SERVICE_OPTS)
if parent_id is not None and len(res) == 0:
raise Http404(
"No link found for %s-%s to %s-%s"
% (parent_type, parent_id, child_type, child_ids)
)
return link_type, res
def create_link(parent_type, parent_id, child_type, child_id):
"""This is just used internally by api_link DELETE below"""
if parent_type == "experimenter":
if child_type == "dataset" or child_type == "plate":
# This is actually not a link that needs creating, this
# dataset/plate is an orphan
return "orphan"
if parent_type == "project":
project = ProjectI(int(parent_id), False)
if child_type == "dataset":
dataset = DatasetI(int(child_id), False)
link = ProjectDatasetLinkI()
link.setParent(project)
link.setChild(dataset)
return link
elif parent_type == "dataset":
dataset = DatasetI(int(parent_id), False)
if child_type == "image":
image = ImageI(int(child_id), False)
link = DatasetImageLinkI()
link.setParent(dataset)
link.setChild(image)
return link
elif parent_type == "screen":
screen = ScreenI(int(parent_id), False)
if child_type == "plate":
plate = PlateI(int(child_id), False)
link = ScreenPlateLinkI()
link.setParent(screen)
link.setChild(plate)
return link
elif parent_type == "tagset":
if child_type == "tag":
link = AnnotationAnnotationLinkI()
link.setParent(TagAnnotationI(int(parent_id), False))
link.setChild(TagAnnotationI(int(child_id), False))
return link
return None
def get_objects_owners(conn, child_type, child_ids):
"""
Returns a dict of child_id: owner_id
"""
if child_type == "tag":
child_type = "Annotation"
owners = {}
for obj in conn.getObjects(child_type, child_ids):