Package omeroweb :: Package webmobile :: Module webmobile_util
[hide private]
[frames] | no frames]

Source Code for Module omeroweb.webmobile.webmobile_util

  1   
  2  from datetime import datetime, timedelta 
  3  from django.core.urlresolvers import reverse 
  4   
  5  import omero 
  6  from omero.rtypes import rlong, rint, rtime 
  7  from omero.gateway import ImageWrapper, ProjectWrapper, AnnotationWrapper, BlitzObjectWrapper, DatasetWrapper 
  8  from webclient.webclient_gateway import OmeroWebGateway 
  9   
 10   
 11           
12 -def listMostRecentObjects(conn, limit, obj_types=None, eid=None):
13 """ 14 Get the most recent objects supported by the timeline service: obj_types are 15 ['Project', 'Dataset', 'Image', 'Annotation'), Specifying the 16 number of each you want 'limit', belonging to the specified experimenter 'eid' 17 or current Group if 'eid' is None. 18 """ 19 20 from datetime import datetime 21 now = datetime.now() 22 23 tm = conn.getTimelineService() 24 p = omero.sys.Parameters() 25 p.map = {} 26 f = omero.sys.Filter() 27 if eid: 28 f.ownerId = rlong(eid) 29 else: 30 f.groupId = rlong(conn.getEventContext().groupId) 31 f.limit = rint(limit) 32 p.theFilter = f 33 34 types = {'Image':ImageWrapper, 'Project':ProjectWrapper, 'Dataset':DatasetWrapper} 35 recent = tm.getMostRecentObjects(None, p, False) 36 37 recentItems = [] 38 for r in recent: # 'Image', 'Project', 'Dataset', 'Annotation', 'RenderingSettings' 39 if obj_types and r not in obj_types: 40 continue 41 for value in recent[r]: 42 if r == 'Annotation': 43 recentItems.append(AnnotationWrapper._wrap(conn, value)) 44 elif r in types: 45 recentItems.append( types[r](conn, value) ) 46 else: 47 pass # RenderingSettings 48 # recentItems.append( BlitzObjectWrapper(conn, value) ) 49 50 if obj_types == None or 'Annotation' in obj_types: 51 anns = listMostRecentAnnotations(conn, limit, eid) 52 recentItems.extend(anns) 53 54 recentItems.sort(key = lambda x: x.updateEventDate()) 55 recentItems.reverse() 56 return recentItems
57 58
59 -def listMostRecentAnnotations (conn, limit, eid=None):
60 """ 61 Retrieve most recent annotations available 62 63 @return: Generator yielding BlitzObjectWrapper 64 @rtype: L{BlitzObjectWrapper} generator 65 """ 66 67 tm = conn.getTimelineService() 68 p = omero.sys.Parameters() 69 p.map = {} 70 f = omero.sys.Filter() 71 if eid: 72 f.ownerId = rlong(eid) 73 else: 74 f.groupId = rlong(conn.getEventContext().groupId) 75 f.limit = rint(limit) 76 p.theFilter = f 77 anns = [] 78 79 # get ALL parent-types, child-types, namespaces: 80 annTypes = ['LongAnnotation', 'TagAnnotation', 'CommentAnnotation'] # etc. Only query 1 at at time! 81 for at in annTypes: 82 for a in tm.getMostRecentAnnotationLinks(None, [at], None, p): 83 # TODO: maybe load parent for each link here 84 wrapper = AnnotationWrapper._wrap(conn, a.child, a) 85 anns.append(wrapper) 86 return anns
87 88
89 -def formatTimeAgo(eventDate):
90 """ 91 Formats a datetime wrt 'now'. 92 E.g. '3 hours 25 mins ago', 'Yesterday at 18:30', 'Friday 14 Jan at 10.44' 93 """ 94 95 now = datetime.now() 96 year = now.year 97 month = now.month 98 day = now.day 99 one_day = timedelta(1) 100 yesterday_start = datetime(year, month, day) - timedelta(1) 101 ago = now - eventDate 102 103 if ago < one_day: 104 hh, rem = divmod(ago.seconds, 3600) 105 mm, rem = divmod(rem, 60) 106 if hh == 0: 107 return "%s mins ago" % mm 108 return "%s hours %s mins ago" % (hh, mm) 109 elif eventDate > yesterday_start: 110 return "Yesterday at %s" % eventDate.strftime("%H:%M") 111 else: 112 return "%s" % eventDate.strftime("%A, %d %b at %H:%M")
113 114
115 -class RecentEvent(object):
116
117 - def __init__(self, blitzWrapper, roi=None):
118 119 self.obj = blitzWrapper 120 self.display_type = None 121 self.url = None 122 self.parent_type = None # for annotations 123 self.parent_id = None 124 self.parent_name = None # only set if parent is loaded 125 self.link_created = None 126 self.link_owner = None 127 self.roi_owner = None # only set if ROI is set 128 129 # Pick a suitable display name for the object. E.g. 'Image', 'Comment' etc. 130 annTypes = {omero.gateway.CommentAnnotationWrapper:'Comment', 131 omero.gateway.FileAnnotationWrapper:'File', 132 omero.gateway.TimestampAnnotationWrapper:'Timestamp', 133 omero.gateway.BooleanAnnotationWrapper:'Boolean', 134 omero.gateway.TagAnnotationWrapper:'Tag', 135 omero.gateway.LongAnnotationWrapper:'Long', 136 omero.gateway.DoubleAnnotationWrapper:'Double'} 137 modelTypes = {omero.model.ImageI:'Image', 138 omero.model.DatasetI:'Dataset', 139 omero.model.ProjectI:'Project'} 140 # Annotations.. 141 if self.obj.__class__ in annTypes: 142 self.display_type = annTypes[self.obj.__class__] 143 try: 144 self.parent_id = blitzWrapper.link.parent.id.val 145 self.parent_type = modelTypes[blitzWrapper.link.parent.__class__] 146 self.parent_name = blitzWrapper.link.parent.name.val 147 cEvt = blitzWrapper.link.details.creationEvent._time.val 148 self.link_created = formatTimeAgo(datetime.fromtimestamp(cEvt/1000)) 149 self.link_owner = "%s %s" % (blitzWrapper.link.details.owner.firstName.val, blitzWrapper.link.details.owner.lastName.val) 150 except: 151 pass 152 153 # Handle special case of Long annotations being 'Ratings' 154 if self.display_type == 'Long' and self.obj.ns: 155 if self.obj.ns == "openmicroscopy.org/omero/insight/rating": 156 self.display_type = 'Rating' 157 else: 158 self.display_type = blitzWrapper.OMERO_CLASS 159 160 # Create a suitable link, either to Object itself, or to the Parent (for comments, rating) 161 def getLinkToObject(modelObject): 162 if modelObject.__class__ == omero.model.ImageI: 163 return reverse('webmobile_image', kwargs={'imageId':modelObject.id.val}) 164 if modelObject.__class__ == omero.model.DatasetI: 165 return reverse('webmobile_dataset_details', kwargs={'id':modelObject.id.val}) 166 if modelObject.__class__ == omero.model.ProjectI: 167 return reverse('webmobile_project_details', kwargs={'id':modelObject.id.val})
168 169 if self.display_type in ['Image', 'Project', 'Dataset']: 170 self.url = getLinkToObject(blitzWrapper._obj) 171 elif self.display_type in ['Rating', 'Comment', 'Tag']: 172 if blitzWrapper.link: 173 self.url = getLinkToObject(blitzWrapper.link.parent) 174 175 # for Images where we also have an ROI, set the creation date of the ROI. 176 if roi: 177 cEvt = roi.details.creationEvent._time.val 178 self.timeAgo = formatTimeAgo(datetime.fromtimestamp(cEvt/1000)) 179 self.roi_owner = "%s %s" % (roi.details.owner.firstName.val, roi.details.owner.lastName.val) 180 else: 181 self.timeAgo = formatTimeAgo(blitzWrapper.updateEventDate())
182 183
184 -def listCollabAnnotations(conn, myData=True, limit=10):
185 """ 186 Lists the most recent annotations BY other users on YOUR images etc. 187 """ 188 189 eid = conn.getEventContext().userId 190 queryService = conn.getQueryService() 191 params = omero.sys.ParametersI() 192 params.addLong("eid", eid); 193 f = omero.sys.Filter() 194 f.limit = rint(limit) 195 params.theFilter = f 196 197 if myData: # want annotation links NOT owned, where parent IS owned 198 selection = "where owner.id = :eid and linkOwner.id != :eid " 199 else: # want annotation links owned by me, on data NOT owned by me 200 selection = "where owner.id != :eid and linkOwner.id = :eid " 201 202 query = "select al from ImageAnnotationLink as al " \ 203 "join fetch al.child as annot " \ 204 "join fetch al.parent as parent " \ 205 "join fetch parent.details.owner as owner " \ 206 "join fetch al.details.owner as linkOwner " \ 207 "join fetch al.details.creationEvent as event %s" \ 208 "order by event desc" % selection 209 imageLinks = queryService.findAllByQuery(query, params) 210 211 return [RecentEvent (AnnotationWrapper._wrap(conn, a.child, a) ) for a in imageLinks]
212 213
214 -def listRois(conn, eid=None, limit=10):
215 """ 216 List the most recently created ROIs, optionally filtering by owner. 217 Returns a list of RecentObjects wrapping the linked Images. 218 """ 219 220 queryService = conn.getQueryService() 221 params = omero.sys.ParametersI() 222 f = omero.sys.Filter() 223 f.limit = rint(limit) 224 params.theFilter = f 225 226 if eid is not None: 227 params.map["eid"] = rlong(long(eid)) 228 eidSelect = "where roi.details.owner.id=:eid " 229 else: eidSelect = "" 230 231 query = "select roi from Roi as roi " \ 232 "join fetch roi.image as image " \ 233 "join fetch roi.details.owner " \ 234 "join fetch roi.details.creationEvent as event %s" \ 235 "order by event desc" % eidSelect 236 237 rois = queryService.findAllByQuery(query, params) 238 return [RecentEvent (ImageWrapper(conn, r.image), r) for r in rois]
239