/
views.py
executable file
·2792 lines (2463 loc) · 123 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-2011 University of Dundee.
#
# 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/>.
#
# Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2008.
#
# Version: 1.0
#
''' 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 sys
import copy
import re
import os
import calendar
import cStringIO
import datetime
import httplib
import Ice
import locale
import logging
import traceback
import shutil
import zipfile
from time import time
from thread import start_new_thread
from omero_version import omero_version
import omero, omero.scripts
from omero.rtypes import *
from django.conf import settings
from django.contrib.sessions.backends.cache import SessionStore
from django.core import template_loader
from django.core.cache import cache
from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponseServerError, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext as Context
from django.utils import simplejson
from django.utils.http import urlencode
from django.views.defaults import page_not_found, server_error
from django.views import debug
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_str
from django.core.servers.basehttp import FileWrapper
from webclient.webclient_gateway import OmeroWebGateway
from webclient_http import HttpJavascriptRedirect, HttpJavascriptResponse, HttpLoginRedirect
from webclient_utils import _formatReport, _purgeCallback
from forms import ShareForm, BasketShareForm, \
ContainerForm, ContainerNameForm, ContainerDescriptionForm, \
CommentAnnotationForm, TagsAnnotationForm, \
UsersForm, ActiveGroupForm, \
MetadataFilterForm, MetadataDetectorForm, MetadataChannelForm, \
MetadataEnvironmentForm, MetadataObjectiveForm, MetadataObjectiveSettingsForm, MetadataStageLabelForm, \
MetadataLightSourceForm, MetadataDichroicForm, MetadataMicroscopeForm, \
FilesAnnotationForm, WellIndexForm
from controller import BaseController
from controller.index import BaseIndex
from controller.basket import BaseBasket
from controller.container import BaseContainer
from controller.help import BaseHelp
from controller.history import BaseCalendar
from controller.impexp import BaseImpexp
from controller.search import BaseSearch
from controller.share import BaseShare
from omeroweb.connector import Server
from omeroweb.webadmin.forms import LoginForm
from omeroweb.webadmin.webadmin_utils import toBoolean, upgradeCheck
from omeroweb.webgateway import views as webgateway_views
from omeroweb.feedback.views import handlerInternalError
from omeroweb.webclient.decorators import login_required
from omeroweb.webclient.decorators import render_response
from omeroweb.connector import Connector
from omeroweb.decorators import ConnCleaningHttpResponse
logger = logging.getLogger(__name__)
logger.info("INIT '%s'" % os.getpid())
# helper method
def getIntOrDefault(request, name, default):
try:
index = int(request.REQUEST.get(name, default))
except ValueError:
index = 0
return index
################################################################################
# views controll
def login(request):
"""
Webclient Login - 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.
"""
request.session.modified = True
conn = None
error = None
server_id = request.REQUEST.get('server')
form = LoginForm(data=request.REQUEST.copy())
useragent = 'OMERO.web'
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
server_id = form.cleaned_data['server']
is_secure = toBoolean(form.cleaned_data['ssl'])
connector = Connector(server_id, is_secure)
# TODO: version check should be done on the low level, see #5983
if server_id is not None and username is not None and password is not None \
and connector.check_version(useragent):
conn = connector.create_connection(useragent, username, password)
if conn is not None:
# Check if user is in "user" group
userGroupId = conn.getAdminService().getSecurityRoles().userGroupId
if userGroupId in conn.getEventContext().memberOfGroups:
request.session['connector'] = connector
upgradeCheck()
# if 'active_group' remains in session from previous login, check it's valid for this user
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']
# do we ned to display server version ?
# server_version = conn.getServerVersion()
if request.REQUEST.get('noredirect'):
return HttpResponse('OK')
url = request.REQUEST.get("url")
if url is not None and len(url) != 0:
return HttpResponseRedirect(url)
else:
return HttpResponseRedirect(reverse("webindex"))
elif username == "guest":
error = "Guest account is for internal OMERO use only. Not for login."
else:
error = "This user is not active."
if request.method == 'POST' and server_id is not None:
connector = Connector(server_id, True)
if not connector.is_server_up(useragent):
error = "Server is not responding, please contact administrator."
elif not connector.check_version(useragent):
error = "Client version does not match server, please contact administrator."
else:
error = "Connection not available, please check your user name and password."
url = request.REQUEST.get("url")
template = "webclient/login.html"
if request.method != 'POST':
if server_id is not None:
initial = {'server': unicode(server_id)}
form = LoginForm(initial=initial)
else:
form = LoginForm()
context = {"version": omero_version, 'error':error, 'form':form}
if url is not None and len(url) != 0:
context['url'] = urlencode({'url':url})
t = template_loader.get_template(template)
c = Context(request, context)
rsp = t.render(c)
return HttpResponse(rsp)
@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")
@login_required()
@render_response()
def feed(request, conn=None, **kwargs):
"""
Viewing this page doesn't perform any action. All we do here is assemble various data for display.
Last imports, tag cloud etc are retrived via separate AJAX calls.
"""
template = "webclient/index/index.html"
controller = BaseIndex(conn)
context = {'controller':controller}
context['template'] = template
return context
@login_required()
@render_response()
def index_last_imports(request, conn=None, **kwargs):
"""
Gets the most recent imports - Used in an AJAX call by home page.
"""
controller = BaseIndex(conn)
controller.loadLastAcquisitions()
context = {'controller':controller}
context['template'] = "webclient/index/index_last_imports.html"
return context
@login_required()
@render_response()
def index_most_recent(request, conn=None, **kwargs):
""" Gets the most recent 'shares' and 'share' comments. Used by the homepage via AJAX call """
controller = BaseIndex(conn)
controller.loadMostRecent()
context = {'controller':controller}
context['template'] = "webclient/index/index_most_recent.html"
return context
@login_required()
@render_response()
def index_tag_cloud(request, conn=None, **kwargs):
""" Gets the most used Tags. Used by the homepage via AJAX call """
controller = BaseIndex(conn)
controller.loadTagCloud()
context = {'controller':controller }
context['template'] = "webclient/index/index_tag_cloud.html"
return context
@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)
url = url or reverse("webindex")
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 = request.REQUEST.get('active_group')
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
request.session['imageInBasket'] = set() # empty basket
request.session['basket_counter'] = 0
@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.session.get('active_group') is not None:
try:
conn.setDefaultGroup(request.session.get('active_group'))
except:
logger.error('Exception during logout.', exc_info=True)
try:
try:
conn.seppuku()
except:
logger.error('Exception during logout.', exc_info=True)
finally:
request.session.flush()
return HttpResponseRedirect(reverse("webindex"))
###########################################################################
@login_required()
@render_response()
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
if menu == 'userdata':
template = "webclient/data/containers.html"
elif menu == 'usertags':
template = "webclient/data/container_tags.html"
else:
template = "webclient/%s/%s.html" % (menu,menu)
#tree support
init = {'initially_open':None, 'initially_select': []}
first_sel = None
initially_open_owner = None
# E.g. backwards compatible support for path=project=51|dataset=502|image=607 (select the image)
path = request.REQUEST.get('path', '')
i = path.split("|")[-1]
if i.split("=")[0] in ('project', 'dataset', 'image', 'screen', 'plate', 'tag'):
init['initially_select'].append(str(i).replace("=",'-')) # Backwards compatible with image=607 etc
# Now we support show=image-607|image-123 (multi-objects selected)
show = request.REQUEST.get('show', '')
for i in show.split("|"):
if i.split("-")[0] in ('project', 'dataset', 'image', 'screen', 'plate', 'tag', 'acquisition', 'run', 'well'):
i = i.replace('run', 'acquisition') # alternatives for 'acquisition'
init['initially_select'].append(str(i))
if len(init['initially_select']) > 0:
# tree hierarchy open to first selected object
init['initially_open'] = [ init['initially_select'][0] ]
first_obj, first_id = init['initially_open'][0].split("-",1)
# if we're showing a tag, make sure we're on the tags page...
if first_obj == "tag" and menu != "usertags":
return HttpResponseRedirect(reverse(viewname="load_template", args=['usertags']) + "?show=" + init['initially_select'][0])
try:
conn.SERVICE_OPTS.setOmeroGroup('-1') # set context to 'cross-group'
if first_obj == "tag":
first_sel = conn.getObject("TagAnnotation", long(first_id))
else:
first_sel = conn.getObject(first_obj, long(first_id))
initially_open_owner = first_sel.details.owner.id.val
# Wells aren't in the tree, so we need parent...
if first_obj == "well":
parentNode = first_sel.getWellSample().getPlateAcquisition()
ptype = "acquisition"
if parentNode is None: # No Acquisition for this well...
parentNode = first_sel.getParent() #...use Plate instead
ptype = "plate"
first_sel = parentNode
init['initially_open'] = ["%s-%s" % (ptype, parentNode.getId())]
init['initially_select'] = init['initially_open'][:]
except:
pass # invalid id
if first_obj not in ("project", "screen"):
# need to see if first item has parents
if first_sel is not None:
for p in first_sel.getAncestry():
if first_obj == "tag": # parents of tags must be tags (no OMERO_CLASS)
init['initially_open'].insert(0, "tag-%s" % p.getId())
else:
init['initially_open'].insert(0, "%s-%s" % (p.OMERO_CLASS.lower(), p.getId()))
initially_open_owner = p.details.owner.id.val
if init['initially_open'][0].split("-")[0] == 'image':
init['initially_open'].insert(0, "orphaned-0")
# need to be sure that tree will be correct omero.group
if first_sel is not None:
switch_active_group(request, first_sel.details.group.id.val)
# search support
if menu == "search" and request.REQUEST.get('search_query'):
init['query'] = str(request.REQUEST.get('search_query')).replace(" ", "%20")
# get url without request string - used to refresh page after switch user/group etc
url = reverse(viewname="load_template", args=[menu])
manager = BaseContainer(conn)
# validate experimenter is in the active group
active_group = request.session.get('active_group') or conn.getEventContext().groupId
# prepare members of group...
s = conn.groupSummary(active_group)
leaders = s["leaders"]
members = s["colleagues"]
userIds = [u.id for u in leaders]
userIds.extend( [u.id for u in members] )
users = []
if len(leaders) > 0:
users.append( ("Owners", leaders) )
if len(members) > 0:
users.append( ("Members", members) )
users = tuple(users)
# check any change in experimenter...
user_id = request.REQUEST.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 = long(user_id)
except:
user_id = None
if user_id is not None:
form_users = UsersForm(initial={'users': users, 'empty_label':None, 'menu':menu}, data=request.REQUEST.copy())
if not form_users.is_valid():
if 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
if conn.isAdmin(): # Admin can see all groups
myGroups = [g for g in conn.getObjects("ExperimenterGroup") if g.getName() not in ("user", "guest")]
else:
myGroups = list(conn.getGroupsMemberOf())
myGroups.sort(key=lambda x: x.getName().lower())
new_container_form = ContainerForm()
context = {'init':init, 'myGroups':myGroups, 'new_container_form':new_container_form}
context['groups'] = myGroups
context['active_group'] = conn.getObject("ExperimenterGroup", long(active_group))
for g in context['groups']:
g.groupSummary() # load leaders / members
context['active_user'] = conn.getObject("Experimenter", long(user_id))
context['isLeader'] = conn.isLeader()
context['current_url'] = url
context['template'] = template
return context
@login_required(setGroupContext=True)
@render_response()
def load_data(request, o1_type=None, o1_id=None, o2_type=None, o2_id=None, o3_type=None, o3_id=None, conn=None, **kwargs):
"""
This loads data for the tree, via AJAX calls.
The template is specified by query string. E.g. icon, table, tree.
By default this loads Projects and Datasets.
E.g. /load_data?view=tree provides data for the tree as <li>.
"""
# get page
page = getIntOrDefault(request, 'page', 1)
# get view
view = str(request.REQUEST.get('view', None))
# get index of the plate
index = getIntOrDefault(request, 'index', 0)
# prepare data. E.g. kw = {} or {'dataset': 301L} or {'project': 151L, 'dataset': 301L}
kw = dict()
if o1_type is not None:
if o1_id is not None and o1_id > 0:
kw[str(o1_type)] = long(o1_id)
else:
kw[str(o1_type)] = bool(o1_id)
if o2_type is not None and o2_id > 0:
kw[str(o2_type)] = long(o2_id)
if o3_type is not None and o3_id > 0:
kw[str(o3_type)] = long(o3_id)
try:
manager= BaseContainer(conn, **kw)
except AttributeError, x:
return handlerInternalError(request, x)
# prepare forms
filter_user_id = request.session.get('user_id')
form_well_index = None
context = {'manager':manager, 'form_well_index':form_well_index, 'index':index}
# load data & template
template = None
if kw.has_key('orphaned'):
manager.listOrphanedImages(filter_user_id, page)
if view =='icon':
template = "webclient/data/containers_icon.html"
else:
template = "webclient/data/container_subtree.html"
elif len(kw.keys()) > 0 :
if kw.has_key('dataset'):
load_pixels = (view == 'icon') # we need the sizeX and sizeY for these
filter_user_id = None # Show images belonging to all users
manager.listImagesInDataset(kw.get('dataset'), filter_user_id, page, load_pixels=load_pixels)
if view =='icon':
template = "webclient/data/containers_icon.html"
else:
template = "webclient/data/container_subtree.html"
elif kw.has_key('plate') or kw.has_key('acquisition'):
if view == 'tree': # Only used when pasting Plate into Screen - load Acquisition in tree
template = "webclient/data/container_subtree.html"
else:
fields = manager.getNumberOfFields()
if fields is not None:
form_well_index = WellIndexForm(initial={'index':index, 'range':fields})
if index == 0:
index = fields[0]
show = request.REQUEST.get('show', None)
if show is not None:
select_wells = [w.split("-")[1] for w in show.split("|") if w.startswith("well-")]
context['select_wells'] = ",".join(select_wells)
context['baseurl'] = reverse('webgateway').rstrip('/')
context['form_well_index'] = form_well_index
template = "webclient/data/plate.html"
else:
manager.listContainerHierarchy(filter_user_id)
if view =='tree':
template = "webclient/data/containers_tree.html"
elif view =='icon':
template = "webclient/data/containers_icon.html"
else:
template = "webclient/data/containers.html"
context['template_view'] = view
context['isLeader'] = conn.isLeader()
context['template'] = template
return context
@login_required(setGroupContext=True)
@render_response()
def load_chgrp_target(request, group_id, target_type, conn=None, **kwargs):
""" Loads a tree for user to pick target Project, Dataset or Screen """
# filter by group (not switching group)
conn.SERVICE_OPTS.setOmeroGroup(int(group_id))
manager= BaseContainer(conn)
manager.listContainerHierarchy()
template = 'webclient/data/chgrp_target_tree.html'
show_projects = target_type in ('project', 'dataset')
context = {'manager': manager, 'target_type': target_type, 'show_projects':show_projects, 'template': template}
return context
@login_required(setGroupContext=True)
@render_response()
def load_searching(request, form=None, conn=None, **kwargs):
"""
Handles AJAX calls to search
"""
manager = BaseSearch(conn)
# form = 'form' if we are searching. Get query from request...
if form is not None:
query_search = request.REQUEST.get('query').replace("+", " ")
template = "webclient/search/search_details.html"
onlyTypes = list()
if request.REQUEST.get('projects') is not None and request.REQUEST.get('projects') == 'on':
onlyTypes.append('projects')
if request.REQUEST.get('datasets') is not None and request.REQUEST.get('datasets') == 'on':
onlyTypes.append('datasets')
if request.REQUEST.get('images') is not None and request.REQUEST.get('images') == 'on':
onlyTypes.append('images')
if request.REQUEST.get('plates') is not None and request.REQUEST.get('plates') == 'on':
onlyTypes.append('plates')
if request.REQUEST.get('screens') is not None and request.REQUEST.get('screens') == 'on':
onlyTypes.append('screens')
startdate = request.REQUEST.get('startdateinput', None)
startdate = startdate is not None and smart_str(startdate) or None
enddate = request.REQUEST.get('enddateinput', None)
enddate = enddate is not None and smart_str(enddate) or None
date = None
if startdate is not None:
if enddate is None:
enddate = startdate
date = "%s_%s" % (startdate, enddate)
# by default, if user has not specified any types:
if len(onlyTypes) == 0:
onlyTypes = ['images']
# search is carried out and results are stored in manager.containers.images etc.
manager.search(query_search, onlyTypes, date)
else:
# simply display the search home page.
template = "webclient/search/search.html"
# batch query for searching wells in plates
batch_query = request.REQUEST.get('batch_query')
if batch_query is not None:
delimiter = request.REQUEST.get('delimiter')
delimiter = delimiter.decode("string_escape")
batch_query = batch_query.split("\n")
batch_query = [query.split(delimiter) for query in batch_query]
template = "webclient/search/search_details.html"
manager.batch_search(batch_query)
context = {'manager':manager}
context['template'] = template
return context
@login_required(setGroupContext=True)
@render_response()
def load_data_by_tag(request, o_type=None, o_id=None, conn=None, **kwargs):
"""
Loads data for the tag tree and center panel.
Either get the P/D/I etc under tags, or the images etc under a tagged Dataset or Project.
@param o_type 'tag' or 'project', 'dataset'.
"""
if request.REQUEST.get("o_type") is not None and len(request.REQUEST.get("o_type")) > 0:
o_type = request.REQUEST.get("o_type")
try:
o_id = long(request.REQUEST.get("o_id"))
except:
pass
# check view
view = request.REQUEST.get("view")
# the index of a field within a well
index = getIntOrDefault(request, 'index', 0)
# prepare forms
filter_user_id = request.session.get('user_id')
# prepare data
kw = dict()
if o_type is not None and o_id > 0:
kw[str(o_type)] = long(o_id)
try:
manager= BaseContainer(conn, **kw)
except AttributeError, x:
return handlerInternalError(request, x)
if o_id is not None:
if o_type == "tag":
manager.loadDataByTag()
if view == "tree":
template = "webclient/data/container_tags_containers.html"
elif view == "icon":
template = "webclient/data/containers_icon.html"
elif o_type == "dataset":
manager.listImagesInDataset(o_id, filter_user_id)
template = "webclient/data/container_tags_subtree.html"
else:
manager.loadTags(filter_user_id)
template = "webclient/data/container_tags_tree.html"
# load data
form_well_index = None
context = {'manager':manager}
context['template_view'] = view
context['isLeader'] = conn.isLeader()
context['template'] = template
return context
@login_required()
@render_response()
def open_astex_viewer(request, obj_type, obj_id, conn=None, **kwargs):
"""
Opens the Open Astex Viewer applet, to display volume masks in a couple of formats:
- mrc.map files that are attached to images. obj_type = 'file'
- Convert OMERO image to mrc on the fly. obj_type = 'image_8bit' or 'image'
In this case, we may use 'scipy' to scale the image volume.
"""
# can only populate these for 'image'
image = None
data_storage_mode = ""
pixelRange = None # (min, max) values of the raw data
contourSliderInit, contourSliderIncr = None, None
sizeOptions = None # only give user choice if we need to scale down (and we CAN scale with scipy)
# If we convert to 8bit map, subtract dataOffset, multiply by mapPixelFactor add mapOffset. (used for js contour controls)
if obj_type == 'file':
ann = conn.getObject("Annotation", obj_id)
if ann is None:
return handlerInternalError(request, "Can't find file Annotation ID %s as data source for Open Astex Viewer." % obj_id)
# determine mapType by name
imageName = ann.getFileName()
if imageName.endswith(".bit"):
data_url = reverse("open_astex_bit", args=[obj_id])
else:
data_url = reverse("open_astex_map", args=[obj_id])
elif obj_type in ('image', 'image_8bit'):
image = conn.getObject("Image", obj_id) # just check the image exists
if image is None:
return handlerInternalError(request, "Can't find image ID %s as data source for Open Astex Viewer." % obj_id)
imageName = image.getName()
c = image.getChannels()[0]
# By default, scale to 120 ^3. Also give option to load 'bigger' map or full sized
DEFAULTMAPSIZE = 120
BIGGERMAPSIZE = 160
targetSize = DEFAULTMAPSIZE * DEFAULTMAPSIZE * DEFAULTMAPSIZE
biggerSize = BIGGERMAPSIZE * BIGGERMAPSIZE * BIGGERMAPSIZE
imgSize = image.getSizeX() * image.getSizeY() * image.getSizeZ()
if imgSize > targetSize:
try:
import scipy.ndimage
sizeOptions = {}
factor = float(targetSize)/ imgSize
f = pow(factor,1.0/3)
sizeOptions["small"] = {'x':image.getSizeX() * f, 'y':image.getSizeY() * f, 'z':image.getSizeZ() * f, 'size':DEFAULTMAPSIZE}
if imgSize > biggerSize:
factor2 = float(biggerSize)/ imgSize
f2 = pow(factor2,1.0/3)
sizeOptions["medium"] = {'x':image.getSizeX() * f2, 'y':image.getSizeY() * f2, 'z':image.getSizeZ() * f2, 'size':BIGGERMAPSIZE}
else:
sizeOptions["full"] = {'x':image.getSizeX(), 'y':image.getSizeY(), 'z':image.getSizeZ()}
except ImportError:
DEFAULTMAPSIZE = 0 # don't try to resize the map (see image_as_map)
pass
pixelRange = (c.getWindowMin(), c.getWindowMax())
contourSliderInit = (pixelRange[0] + pixelRange[1])/2 # best guess as starting position for contour slider
def calcPrecision(range):
dec=0
if (range == 0): dec = 0
elif (range < 0.0000001): dec = 10
elif (range < 0.000001): dec = 9
elif (range < 0.00001): dec = 8
elif (range < 0.0001): dec = 7
elif (range < 0.001): dec = 6
elif (range < 0.01): dec = 5
elif (range < 0.1): dec = 4
elif (range < 1.0): dec = 3
elif (range < 10.0): dec = 2
elif (range < 100.0): dec = 1
return dec
dec = calcPrecision(pixelRange[1]-pixelRange[0])
contourSliderIncr = "%.*f" % (dec,abs((pixelRange[1]-pixelRange[0])/128.0))
if obj_type == 'image_8bit':
data_storage_mode = 1
data_url = reverse("webclient_image_as_map_8bit", args=[obj_id, DEFAULTMAPSIZE])
else:
if image.getPrimaryPixels().getPixelsType.value == 'float':
data_storage_mode = 2
else:
data_storage_mode = 1 # E.g. uint16 image will get served as 8bit map
data_url = reverse("webclient_image_as_map", args=[obj_id, DEFAULTMAPSIZE])
context = {'data_url': data_url, "image": image,
"sizeOptions":sizeOptions, "contourSliderInit":contourSliderInit, "contourSliderIncr":contourSliderIncr,
"data_storage_mode": data_storage_mode,'pixelRange':pixelRange}
context['template'] = 'webclient/annotations/open_astex_viewer.html'
return context
@login_required()
@render_response()
def load_metadata_details(request, c_type, c_id, conn=None, share_id=None, **kwargs):
"""
This page is the right-hand panel 'general metadata', first tab only.
Shown for Projects, Datasets, Images, Screens, Plates, Wells, Tags etc.
The data and annotations are loaded by the manager. Display of appropriate data is handled by the template.
"""
# the index of a field within a well
index = getIntOrDefault(request, 'index', 0)
# we only expect a single object, but forms can take multiple objects
images = c_type == "image" and list(conn.getObjects("Image", [c_id])) or list()
datasets = c_type == "dataset" and list(conn.getObjects("Dataset", [c_id])) or list()
projects = c_type == "project" and list(conn.getObjects("Project", [c_id])) or list()
screens = c_type == "screen" and list(conn.getObjects("Screen", [c_id])) or list()
plates = c_type == "plate" and list(conn.getObjects("Plate", [c_id])) or list()
acquisitions = c_type == "acquisition" and list(conn.getObjects("PlateAcquisition", [c_id])) or list()
shares = (c_type == "share" or c_type == "discussion") and [conn.getShare(c_id)] or list()
wells = list()
if c_type == "well":
for w in conn.getObjects("Well", [c_id]):
w.index=index
wells.append(w)
# we simply set up the annotation form, passing the objects to be annotated.
selected = {'images':c_type == "image" and [c_id] or [],
'datasets':c_type == "dataset" and [c_id] or [],
'projects':c_type == "project" and [c_id] or [],
'screens':c_type == "screen" and [c_id] or [],
'plates':c_type == "plate" and [c_id] or [],
'acquisitions':c_type == "acquisition" and [c_id] or [],
'wells':c_type == "well" and [c_id] or [],
'shares':(c_type == "share" or c_type == "discussion") and [c_id] or []}
initial={'selected':selected, 'images':images, 'datasets':datasets, 'projects':projects, 'screens':screens, 'plates':plates, 'acquisitions':acquisitions, 'wells':wells, 'shares': shares}
form_comment = None
figScripts = None
if c_type in ("share", "discussion"):
template = "webclient/annotations/annotations_share.html"
manager = BaseShare(conn, c_id)
manager.getAllUsers(c_id)
manager.getComments(c_id)
form_comment = CommentAnnotationForm(initial=initial)
else:
try:
manager = BaseContainer(conn, index=index, **{str(c_type): long(c_id)})
except AttributeError, x:
return handlerInternalError(request, x)
if share_id is None:
template = "webclient/annotations/metadata_general.html"
manager.annotationList()
figScripts = manager.listFigureScripts()
form_comment = CommentAnnotationForm(initial=initial)
else:
template = "webclient/annotations/annotations_share.html"
if c_type in ("tag"):
context = {'manager':manager}
else:
context = {'manager':manager, 'form_comment':form_comment, 'index':index,
'share_id':share_id}
context['figScripts'] = figScripts
context['template'] = template
context['webclient_path'] = request.build_absolute_uri(reverse('webindex'))
return context
@login_required()
@render_response()
def load_metadata_preview(request, c_type, c_id, conn=None, share_id=None, **kwargs):
"""
This is the image 'Preview' tab for the right-hand panel.
Currently this doesn't do much except launch the view-port plugin using the image Id (and share Id if necessary)
"""
# the index of a field within a well
index = getIntOrDefault(request, 'index', 0)
manager = BaseContainer(conn, index=index, **{str(c_type): long(c_id)})
if c_type == "well":
manager.image = manager.well.getImage(index)
context = {'manager':manager, 'share_id':share_id}
context['template'] = "webclient/annotations/metadata_preview.html"
return context
@login_required()
@render_response()
def load_metadata_hierarchy(request, c_type, c_id, conn=None, **kwargs):
"""
This loads the ancestors of the specified object and displays them in a static tree.
Used by an AJAX call from the metadata_general panel.
"""
# the index of a field within a well
index = getIntOrDefault(request, 'index', 0)
manager = BaseContainer(conn, index=index, **{str(c_type): long(c_id)})
context = {'manager':manager}
context['template'] = "webclient/annotations/metadata_hierarchy.html"
return context
@login_required()
@render_response()
def load_metadata_acquisition(request, c_type, c_id, conn=None, share_id=None, **kwargs):
"""
The acquisition tab of the right-hand panel. Only loaded for images.
TODO: urls regex should make sure that c_type is only 'image' OR 'well'
"""
# the index of a field within a well
index = getIntOrDefault(request, 'index', 0)
try:
if c_type in ("share", "discussion"):
template = "webclient/annotations/annotations_share.html"
manager = BaseShare(conn, c_id)
manager.getAllUsers(c_id)
manager.getComments(c_id)
else:
template = "webclient/annotations/metadata_acquisition.html"
manager = BaseContainer(conn, index=index, **{str(c_type): long(c_id)})
except AttributeError, x:
return handlerInternalError(request, x)
form_environment = None
form_objective = None
form_microscope = None
form_instrument_objectives = list()
form_stageLabel = None
form_filters = list()
form_dichroics = list()
form_detectors = list()
form_channels = list()
form_lasers = list()
# various enums we need for the forms (don't load unless needed)
mediums = None
immersions = None
corrections = None
if c_type == 'well' or c_type == 'image':
if c_type == "well":
manager.image = manager.well.getImage(index)
if share_id is None:
manager.originalMetadata()
manager.channelMetadata()
for theC, ch in enumerate(manager.channel_metadata):
logicalChannel = ch.getLogicalChannel()
if logicalChannel is not None:
channel = dict()
channel['form'] = MetadataChannelForm(initial={'logicalChannel': logicalChannel,
'illuminations': list(conn.getEnumerationEntries("IlluminationI")),
'contrastMethods': list(conn.getEnumerationEntries("ContrastMethodI")),
'modes': list(conn.getEnumerationEntries("AcquisitionModeI"))})
if share_id is None: #9853 Much metadata is not available to 'shares'
lightPath = logicalChannel.getLightPath()
if lightPath is not None:
channel['form_dichroic'] = None
channel['form_excitation_filters'] = list()
channel['form_emission_filters'] = list()
lightPathDichroic = lightPath.getDichroic()
if lightPathDichroic is not None:
channel['form_dichroic'] = MetadataDichroicForm(initial={'dichroic': lightPathDichroic})
filterTypes = list(conn.getEnumerationEntries("FilterTypeI"))
for f in lightPath.getEmissionFilters():
channel['form_emission_filters'].append(MetadataFilterForm(initial={'filter': f,'types':filterTypes}))
for f in lightPath.getExcitationFilters():
channel['form_excitation_filters'].append(MetadataFilterForm(initial={'filter': f,'types':filterTypes}))
if logicalChannel.getDetectorSettings()._obj is not None and logicalChannel.getDetectorSettings().getDetector():
channel['form_detector_settings'] = MetadataDetectorForm(initial={'detectorSettings':logicalChannel.getDetectorSettings(),
'detector': logicalChannel.getDetectorSettings().getDetector(),
'types':list(conn.getEnumerationEntries("DetectorTypeI")),
'binnings':list(conn.getEnumerationEntries("Binning"))})
lightSourceSettings = logicalChannel.getLightSourceSettings()
if lightSourceSettings is not None and lightSourceSettings._obj is not None:
if lightSourceSettings.getLightSource() is not None:
channel['form_light_source'] = MetadataLightSourceForm(initial={'lightSource': lightSourceSettings.getLightSource(),
'lstypes': list(conn.getEnumerationEntries("LaserType")),
'mediums': list(conn.getEnumerationEntries("LaserMediumI")),
'pulses': list(conn.getEnumerationEntries("PulseI"))})
# TODO: We don't display filter sets here yet since they are not populated on Import by BioFormats.
channel['label'] = ch.getLabel()
color = ch.getColor()
channel['color'] = color is not None and color.getHtml() or None
planeInfo = manager.image and manager.image.getPrimaryPixels().copyPlaneInfo(theC=theC, theZ=0)
channel['plane_info'] = list(planeInfo)
form_channels.append(channel)
try:
image = manager.well.getWellSample().image()
except:
image = manager.image
if share_id is None: #9853
if image.getObjectiveSettings() is not None:
# load the enums if needed and create our Objective Form
if mediums is None: mediums = list(conn.getEnumerationEntries("MediumI"))
if immersions is None: immersions = list(conn.getEnumerationEntries("ImmersionI"))
if corrections is None: corrections = list(conn.getEnumerationEntries("CorrectionI"))
form_objective = MetadataObjectiveSettingsForm(initial={'objectiveSettings': image.getObjectiveSettings(),
'objective': image.getObjectiveSettings().getObjective(),
'mediums': mediums, 'immersions': immersions, 'corrections': corrections })
if image.getImagingEnvironment() is not None:
form_environment = MetadataEnvironmentForm(initial={'image': image})
if image.getStageLabel() is not None:
form_stageLabel = MetadataStageLabelForm(initial={'image': image })
instrument = image.getInstrument()
if instrument is not None:
if instrument.getMicroscope() is not None:
form_microscope = MetadataMicroscopeForm(initial={'microscopeTypes':list(conn.getEnumerationEntries("MicroscopeTypeI")), 'microscope': instrument.getMicroscope()})
objectives = instrument.getObjectives()
for o in objectives:
# load the enums if needed and create our Objective Form
if mediums is None: mediums = list(conn.getEnumerationEntries("MediumI"))
if immersions is None: immersions = list(conn.getEnumerationEntries("ImmersionI"))
if corrections is None: corrections = list(conn.getEnumerationEntries("CorrectionI"))