Ejemplo n.º 1
0
    def getTagGroup(self, tagGroupKey, isKey=True):
        metadata = WebServiceObject()
        
        try:
            if isKey:
                group = TagGroup.objects.get(pk__exact=tagGroupKey)
            else:
                group = tagGroupKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_GROUP_KEY
                
        # initialize tagging APIs
        tagGroupAPI = TagGroupAPI(self.user, self.fields)
        tagAPI = TagAPI(user=self.user, unlimited=True)
        geneLinkAPI = GeneLinkAPI(user=self.user, unlimited=True)
        
        group = tagGroupAPI.getTagGroup(group, isKey=False).getObject()

        tags = tagAPI.getTagsByTagGroup(group['id']).getObject()
        for tag in tags:
            geneLinks = geneLinkAPI.getGeneLinksByTag(tag['id']).getObject()
            tag['geneLinks'] = geneLinks
        group['tags'] = tags
            
        metadata.setObject(group)
    
        return metadata
Ejemplo n.º 2
0
    def deleteGeneLink(self, geneLinkKey, isKey=True):
        metadata = WebServiceObject()

        try:
            if (isKey):
                geneLink = GeneLink.objects.get(pk__exact=geneLinkKey)
            else:
                geneLink = geneLinkKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_GENE_LINK_KEY
        except Exception:
            raise Errors.INTERNAL_ERROR

        if not geneLink.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        metadata.limitFields(self.fields)

        metadata.put('id', geneLink.pk)
        metadata.put('tagId', geneLink.tag.pk)
        metadata.put(
            'feature',
            LimitDict(
                self.fields, {
                    'uniqueName': geneLink.feature.uniquename,
                    'name': geneLink.feature.name,
                    'organismId': geneLink.feature.organism.organism_id
                }))

        try:
            geneLink.delete()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))
        return metadata
Ejemplo n.º 3
0
 def deleteGeneLink(self, geneLinkKey, isKey=True):
     metadata = WebServiceObject()
     
     try:
         if (isKey):
             geneLink = GeneLink.objects.get(pk__exact=geneLinkKey)
         else:
             geneLink = geneLinkKey
     except (ObjectDoesNotExist, ValueError):
         raise Errors.INVALID_GENE_LINK_KEY
     except Exception:
         raise Errors.INTERNAL_ERROR
     
     if not geneLink.writePermissions(self.user):
         raise Errors.AUTHENTICATION
     
     metadata.limitFields(self.fields)
             
     metadata.put('id', geneLink.pk)
     metadata.put('tagId', geneLink.tag.pk)
     metadata.put('feature', 
         LimitDict(self.fields, {
             'uniqueName' : geneLink.feature.uniquename,
             'name' : geneLink.feature.name,
             'organismId' : geneLink.feature.organism.organism_id
         })
     )
     
     try:
         geneLink.delete()
     except DatabaseError as e:
         transaction.rollback()
         raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     return metadata
Ejemplo n.º 4
0
    def getImageMetadataByOrganism(self, organismId):
        metadata = WebServiceObject()
        
        if self.user and self.user.is_authenticated():
            allowedImages = Picture.objects.filter(isPrivate=False) | Picture.objects.filter(user__exact=self.user, isPrivate=True) 
        else:
            allowedImages = Picture.objects.filter(isPrivate=False)
        
        defTags = []    
        
        if self.unlimited:
            for orgId in organismId:
                defTags.append(PictureDefinitionTag.objects.filter(organism__exact=orgId, picture__in=allowedImages)[self.offset:])
        else:
            for orgId in organismId:
                defTags.append(PictureDefinitionTag.objects.filter(organism__exact=orgId, picture__in=allowedImages)[self.offset:self.offset + self.limit])   

        closedSet = {}
        imageMetadata = {}
        imageFields = set(['id' , 'url', 'uploadDate', 'description', 'uploadedBy'])
        if self.fields:
            newImageFields = imageFields.intersection(set(self.fields))
            if newImageFields:
                imageFields = newImageFields
        imageMetadataAPI = ImageMetadataAPI(self.user, imageFields)
        
        for orgTags in defTags:
            for tag in orgTags:
                if not closedSet.has_key(tag.picture.pk):
                    closedSet[tag.picture.pk] = imageMetadataAPI.getImageMetadata(tag.picture, False).getObject()
                if imageMetadata.has_key(tag.organism.pk):
                    imageMetadata[tag.organism.pk]['images'].append(closedSet[tag.picture.pk])
                else:
                    imageMetadata[tag.organism.pk] = {
                        'images' : [closedSet[tag.picture.pk]],
                        'organism' : {
                            'id' : tag.organism.pk,
                            'commonName' : tag.organism.common_name,
                            'abbreviation' : tag.organism.abbreviation,
                            'genus' : tag.organism.genus,
                            'species' : tag.organism.species      
                        }
                    }
                    
        if len(imageMetadata) != len(organismId):
            for orgId in organismId:
                if not imageMetadata.has_key(orgId):
                    imageMetadata[orgId] = []
        
        metadata.setObject(LimitDict(self.fields, imageMetadata))
        
        return metadata
Ejemplo n.º 5
0
def getImageMetadata(request):
    renderObj = WebServiceObject()
    if request.GET.has_key('id'):
        # the key for lookup and the image it is attached to
        imageKey = request.GET['id']
        fields = Util.getDelimitedList(request.GET, 'fields')
        getAPI = GetAPI(request.user, fields)
        try:
            renderObj = getAPI.getImageMetadata(imageKey)
        except Errors.WebServiceException as e:
            renderObj.setError(e)
    else:
        renderObj.setError(Errors.NO_IMAGE_KEY)
    
    return renderObj
Ejemplo n.º 6
0
def getImageTags(request):
    renderObj = WebServiceObject()

    # read in crucial parameters
    tagGroupKey = request.GET.get('tagGroupId', None)
    imageKey = request.GET.get('imageId', None)

    # read in optional parameters and initialize the API
    offset = Util.getInt(request.GET, 'offset', 0)
    limit = Util.getInt(request.GET, 'limit', 10)
    unlimited = request.GET.get('unlimited', False)
    fields = Util.getDelimitedList(request.GET, 'fields')
    getAPI = GetAPI(limit, offset, request.user, fields, unlimited)

    if tagGroupKey:
        # the key for lookup and the image it is attached to
        renderObj = getAPI.getTagsByTagGroup(tagGroupKey, isKey=True)
    elif imageKey:
        # the key for lookup and the image it is attached to
        renderObj = getAPI.getTagsByImage(imageKey, isKey=True)
    else:
        # get all the tags
        renderObj = getAPI.getTags()

    return renderObj
Ejemplo n.º 7
0
	def doProcessRender(self, request):
		renderObj = WebServiceObject()
		try:
			if (request.method == "GET"):
				renderObj = API.getOrganisms(request)
			else:
				renderObj.setError(Errors.INVALID_METHOD.setCustom(request.method))
		except Errors.WebServiceException as e:
			renderObj.setError(e)

		self.setJsonObject(renderObj.getObject())
		self.setStatus(renderObj.getCode())
Ejemplo n.º 8
0
    def doProcessRender(self, request):
        renderObj = WebServiceObject()
        try:
            if request.method == "GET":
                renderObj = API.getGeneLink(request)
            elif request.method == "POST":
                renderObj = API.createGeneLink(request)
            elif request.method == "DELETE":
                renderObj = API.deleteGeneLink(request)
            else:
                renderObj.setError(
                    Errors.INVALID_METHOD.setCustom(request.method))
        except Errors.WebServiceException as e:
            renderObj.setError(e)

        self.setJsonObject(renderObj.getObject())
        self.setStatus(renderObj.getCode())
Ejemplo n.º 9
0
	def doProcessRender(self, request):
		renderObj = WebServiceObject()
		try:
			if request.method == "GET":
				renderObj = API.getGeneLink(request)
			elif request.method == "POST":
				renderObj = API.createGeneLink(request)
			elif request.method == "DELETE":
				renderObj = API.deleteGeneLink(request)
			else:
				renderObj.setError(Errors.INVALID_METHOD.setCustom(request.method))
		except Errors.WebServiceException as e:
			renderObj.setError(e)

		self.setJsonObject(renderObj.getObject())
		self.setStatus(renderObj.getCode())
Ejemplo n.º 10
0
def createImageMetadata(request):
    renderObj = WebServiceObject()

    # these should overwrite current metadata
    image = request.FILES.get('image', None)
    description = request.POST.get('description', None)
    altText = request.POST.get('altText', None)
    organisms = Util.getDelimitedList(request.POST, 'organisms')
    fields = Util.getDelimitedList(request.POST, 'fields')

    if image:
        postAPI = PostAPI(request.user, fields)
        renderObj = postAPI.createImageMetadata(image, description, altText,
                                                organisms)
    else:
        raise Errors.MISSING_PARAMETER.setCustom('image')

    return renderObj
Ejemplo n.º 11
0
    def doProcessRender(self, request):
        renderObj = WebServiceObject()
        try:
            if request.method == "GET":
                renderObj = API.getQtl(request)
            elif request.method == "POST":
                print 'test at doProcessRender()'
                renderObj = API.addQtl(request)
            #elif request.method == "PUT":
            #    renderObj = API.updateQtl(request)
            #elif request.method == "DELETE":
            #    renderObj = API.deleteQtl(request)
            else:
                renderObj.setError(
                    Errors.INVALID_METHOD.setCustom(request.method))
        except Errors.WebServiceException as e:
            renderObj.setError(e)

        self.setJsonObject(renderObj.getObject())
        self.setStatus(renderObj.getCode())
Ejemplo n.º 12
0
def getImageMetadata(request):
    renderObj = WebServiceObject()
    if request.GET.has_key('id'):
        # the key for lookup and the image it is attached to
        imageKey = request.GET['id']
        fields = Util.getDelimitedList(request.GET, 'fields')
        getAPI = GetAPI(request.user, fields)
        try:
            renderObj = getAPI.getImageMetadata(imageKey)
        except Errors.WebServiceException as e:
            renderObj.setError(e)
    else:
        renderObj.setError(Errors.NO_IMAGE_KEY)

    return renderObj
Ejemplo n.º 13
0
def editImageMetadata(request):
    renderObj = WebServiceObject()

    # required parameters
    imageKey = request.PUT.get('id', None)
    if not imageKey:
        raise Errors.NO_IMAGE_KEY

    # these should overwrite current metadata
    description = request.PUT.get('description', None)
    altText = request.POST.get('altText', None)
    organisms = Util.getDelimitedList(request.PUT, 'organisms')
    fields = Util.getDelimitedList(request.PUT, 'fields')

    if description or organisms:
        putAPI = PutAPI(request.user, fields)
        renderObj = putAPI.editImageMetadata(imageKey, description, altText,
                                             organisms)
    else:
        raise Errors.NOT_MODIFIED

    return renderObj
Ejemplo n.º 14
0
 def getTag(self, tagKey, isKey=True):
     metadata = WebServiceObject()
     
     try:            
         if (isKey):
             tag = Tag.objects.get(pk__exact=tagKey)
         else:
             tag = tagKey
     except (ObjectDoesNotExist, ValueError):
         raise Errors.INVALID_TAG_KEY
     except Exception:
         raise Errors.INTERNAL_ERROR
         
     if not tag.readPermissions(self.user):
         raise Errors.AUTHENTICATION
     
     metadata.limitFields(self.fields)
     
     if metadata.allowsField('points'):
         tagPoints = TagPoint.objects.filter(tag__exact=tag)
         
         points = []
         
         for tagPoint in tagPoints:
             points.append({
                 'x' : tagPoint.pointX, 
                 'y' : tagPoint.pointY
             })
         
         metadata.put('points', points)
     
     metadata.put('id', tag.pk)
     metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
     metadata.put('name', tag.name)
     
     return metadata
Ejemplo n.º 15
0
    def getImageMetadataByOrganism(self, organismId):
        metadata = WebServiceObject()

        if self.user and self.user.is_authenticated():
            allowedImages = Picture.objects.filter(
                isPrivate=False) | Picture.objects.filter(
                    user__exact=self.user, isPrivate=True)
        else:
            allowedImages = Picture.objects.filter(isPrivate=False)

        defTags = []

        if self.unlimited:
            for orgId in organismId:
                defTags.append(
                    PictureDefinitionTag.objects.filter(
                        organism__exact=orgId,
                        picture__in=allowedImages)[self.offset:])
        else:
            for orgId in organismId:
                defTags.append(
                    PictureDefinitionTag.objects.filter(
                        organism__exact=orgId,
                        picture__in=allowedImages)[self.offset:self.offset +
                                                   self.limit])

        closedSet = {}
        imageMetadata = {}
        imageFields = set(
            ['id', 'url', 'uploadDate', 'description', 'uploadedBy'])
        if self.fields:
            newImageFields = imageFields.intersection(set(self.fields))
            if newImageFields:
                imageFields = newImageFields
        imageMetadataAPI = ImageMetadataAPI(self.user, imageFields)

        for orgTags in defTags:
            for tag in orgTags:
                if not closedSet.has_key(tag.picture.pk):
                    closedSet[
                        tag.picture.pk] = imageMetadataAPI.getImageMetadata(
                            tag.picture, False).getObject()
                if imageMetadata.has_key(tag.organism.pk):
                    imageMetadata[tag.organism.pk]['images'].append(
                        closedSet[tag.picture.pk])
                else:
                    imageMetadata[tag.organism.pk] = {
                        'images': [closedSet[tag.picture.pk]],
                        'organism': {
                            'id': tag.organism.pk,
                            'commonName': tag.organism.common_name,
                            'abbreviation': tag.organism.abbreviation,
                            'genus': tag.organism.genus,
                            'species': tag.organism.species
                        }
                    }

        if len(imageMetadata) != len(organismId):
            for orgId in organismId:
                if not imageMetadata.has_key(orgId):
                    imageMetadata[orgId] = []

        metadata.setObject(LimitDict(self.fields, imageMetadata))

        return metadata
Ejemplo n.º 16
0
    def deleteTag(self, tagKey, isKey=True):
        metadata = WebServiceObject()

        try:
            if (isKey):
                tag = Tag.objects.get(pk__exact=tagKey)
            else:
                tag = tagKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_GENE_LINK_KEY
        except Exception:
            raise Errors.INTERNAL_ERROR

        if not tag.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        metadata.limitFields(self.fields)

        if metadata.allowsField('points'):
            tagPoints = TagPoint.objects.filter(tag__exact=tag)

            points = []

            for tagPoint in tagPoints:
                points.append({'x': tagPoint.pointX, 'y': tagPoint.pointY})

            metadata.put('points', points)

        metadata.put('id', tag.pk)
        metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
        metadata.put('name', tag.name)

        try:
            tag.delete()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))
Ejemplo n.º 17
0
    def getTagGroup(self, tagGroupKey, isKey=True):
        metadata = WebServiceObject()
        
        try:            
            if (isKey):
                tagGroup = TagGroup.objects.get(pk__exact=tagGroupKey)
            else:
                tagGroup = tagGroupKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_GROUP_KEY
        except Exception:
            raise Errors.INTERNAL_ERROR
        
        if not tagGroup.readPermissions(self.user):
            raise Errors.AUTHENTICATION

        metadata.limitFields(self.fields)
                
        metadata.put('id', tagGroup.pk)
        metadata.put('name', tagGroup.name)
        metadata.put('user', tagGroup.user.username)
        metadata.put('dateCreated', tagGroup.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('lastModified', tagGroup.lastModified.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('imageId', tagGroup.picture.pk)
        metadata.put('isPrivate', tagGroup.isPrivate)
        
        return metadata
Ejemplo n.º 18
0
 def createGeneLink(self, tagKey, name=None,  uniqueName=None, organismId=None, isKey=True):
     metadata = WebServiceObject()
     
     try:
         if isKey:
             tag = Tag.objects.get(pk__exact=tagKey)
         else:
             tag = tagKey
     except (ObjectDoesNotExist, ValueError):
         raise Errors.INVALID_TAG_GROUP_KEY
     
     if not tag.writePermissions(self.user):
         raise Errors.AUTHENTICATION 
     
     try:
         feature = None
         if name and organismId:
             feature = Feature.objects.filter(name=name, organism=organismId)
         if uniqueName:
             if feature:
                 feature = feature & Feature.objects.filter(uniquename=uniqueName)
             else:
                 feature = Feature.objects.filter(uniquename=uniqueName)
         
         if not feature:
             error = ""
             if name and organismId:
                 error += "name: " + name + ", organismId: " + organismId
             if uniqueName:
                 comma = ", " if error else ""
                 error += comma + "uniqueName: " + uniqueName
             
             raise Errors.NO_MATCHING_FEATURE.setCustom(error)
         geneLink = GeneLink(tag=tag, feature=feature)
         geneLink.save()
     except DatabaseError as e:
         transaction.rollback()
         raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     
     # limit metadata return
     metadata.limitFields(self.fields)
         
     metadata.put('id', geneLink.pk)
     metadata.put('user', geneLink.user.username)
     metadata.put('tagId', geneLink.tag.pk)
     metadata.put('feature', 
         LimitDict(self.fields, {
             'uniqueName' : geneLink.feature.uniquename,
             'name' : geneLink.feature.name,
             'organismId' : geneLink.feature.organism.organism_id
         })
     )
     
     return metadata
     
     
Ejemplo n.º 19
0
    def createTagGroup(self, imageKey, name, isKey=True):
        metadata = WebServiceObject()

        try:
            if isKey:
                image = Picture.objects.get(pk__exact=imageKey)
            else:
                image = imageKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY

        if not image.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        # start saving the new tag now that it has passed all tests
        tagGroup = TagGroup(name=name, picture=image, user=self.user)
        try:
            tagGroup.save()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))
        # limit metadata return
        metadata.limitFields(self.fields)

        # add new tag to response for success
        metadata.put('id', tagGroup.pk)
        metadata.put('name', tagGroup.name)
        metadata.put('user', tagGroup.user.username)
        metadata.put('dateCreated',
                     tagGroup.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('lastModified',
                     tagGroup.lastModified.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('imageId', tagGroup.picture.pk)
        metadata.put('isPrivate', tagGroup.isPrivate)

        return metadata
Ejemplo n.º 20
0
    def getTag(self, tagKey, isKey=True):
        metadata = WebServiceObject()

        try:
            if (isKey):
                tag = Tag.objects.get(pk__exact=tagKey)
            else:
                tag = tagKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_KEY
        except Exception:
            raise Errors.INTERNAL_ERROR

        if not tag.readPermissions(self.user):
            raise Errors.AUTHENTICATION

        metadata.limitFields(self.fields)

        if metadata.allowsField('points'):
            tagPoints = TagPoint.objects.filter(tag__exact=tag)

            points = []

            for tagPoint in tagPoints:
                points.append({'x': tagPoint.pointX, 'y': tagPoint.pointY})

            metadata.put('points', points)

        metadata.put('id', tag.pk)
        metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
        metadata.put('name', tag.name)

        return metadata
Ejemplo n.º 21
0
    def addNote(self, notes, pn_id, imageKey):
        metadata = WebServiceObject()

        # get picture instance with imageKey
        try:
            image = Picture.objects.get(pk__exact=imageKey)
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY

        if not self.user:
            raise Errors.NO_USER_KEY
        else:
            userID = self.user

        try:
            # save the new note
            if pn_id:
                # update
                pictureNotes = PictureNotes.objects.get(pk__exact=pn_id)
                if pictureNotes:
                    pictureNotes.notes = notes
                    pictureNotes.picture = image
                    pictureNotes.user = userID
                    pictureNotes.save()
                else:
                    # error
                    print 'Error: no picture_notes.pk found!'
            else:
                # add new
                pictureNotes = PictureNotes(notes=notes, picture=image, user=userID)
                pictureNotes.save()

        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        # limit metadata return
        metadata.limitFields(self.fields)

        # add new tag to response for success
        metadata.put('pn_id', pictureNotes.pk)
        metadata.put('picture', pictureNotes.picture.pk)
        metadata.put('notes', pictureNotes.notes)
        metadata.put('user', pictureNotes.user.username)
        metadata.put('dateCreated', pictureNotes.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))

        return metadata
Ejemplo n.º 22
0
    def createImageMetadata(self,
                            image,
                            description,
                            altText,
                            organisms,
                            isKey=True):
        organismsArr = []
        metadata = WebServiceObject()

        if not (self.user and self.user.is_authenticated()):
            raise Errors.AUTHENTICATION
        filetype = imghdr.what(image.file)
        if not filetype or filetype not in set(
            ['gif', 'tiff', 'jpeg', 'bmp', 'png']):
            raise Errors.INVALID_IMAGE_TYPE
        wrappedFile, thumbnailFile, filename, thumbnailName = handleUpload(
            image)

        if self.user.is_staff:
            upload = Picture(user=self.user,
                             isPrivate=False,
                             imageName=wrappedFile.file,
                             thumbnail=thumbnailFile.file)
        else:
            upload = Picture(user=self.user,
                             isPrivate=True,
                             imageName=wrappedFile.file,
                             thumbnail=thumbnailFile.file)

        try:
            upload.save()
        except DatabaseError as e:
            transaction.rollback()
            os.remove(filename)
            os.remove(thumbnailName)
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        os.remove(filename)
        os.remove(thumbnailName)

        # now that image has been properly uploaded add the metadata to it

        organismField = not self.fields or 'organisms' in self.fields

        if organisms:
            newOrganisms = Organism.objects.filter(organism_id__in=organisms)
            newDefTags = []
            for newOrg in newOrganisms:
                newDefTags.append(
                    PictureDefinitionTag(picture=upload, organism=newOrg))
            try:
                for newTag in newDefTags:
                    newTag.save()
                    if organismField:
                        organismsArr.append({
                            'commonName': newTag.organism.common_name,
                            'abbreviation': newTag.organism.abbreviation,
                            'genus': newTag.organism.genus,
                            'species': newTag.organism.species,
                            'id': newTag.organism.pk
                        })
            except DatabaseError as e:
                transaction.rollback()
                raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        if description:
            upload.description = description
            try:
                upload.save()
            except DatabaseError as e:
                transaction.rollback()
                raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        if altText:
            upload.altText = altText
            try:
                upload.save()
            except DatabaseError as e:
                transaction.rollback()
                raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        metadata.limitFields(self.fields)
        # put in the information we care about
        metadata.put('organisms', organismsArr)
        metadata.put('description', upload.description)
        metadata.put('altText', upload.altText)
        metadata.put('uploadedBy', upload.user.username)
        metadata.put('uploadDate',
                     upload.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('url', upload.imageName.url)
        metadata.put('thumbnail', upload.thumbnail.url)
        metadata.put('id', upload.pk)

        return metadata
Ejemplo n.º 23
0
    def editImageMetadata(self, imageKey, description, altText, organisms, isKey=True):
        organismsArr = []
        metadata = WebServiceObject()
        
        try:
            if isKey:
                image = Picture.objects.get(pk__exact=imageKey) 
            else:
                image = imageKey
        
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY
        
        if not image.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        defTags = PictureDefinitionTag.objects.filter(picture__exact=image)
        
        organismField = not self.fields or 'organisms' in self.fields
        
        if organisms:
            newOrganisms = Organism.objects.filter(organism_id__in=organisms)
            newDefTags = []
            for newOrg in newOrganisms:
                newDefTags.append(PictureDefinitionTag(picture=image, organism=newOrg))
            try:
                defTags.delete()
                for newTag in newDefTags:
                    newTag.save()
                    if organismField:
                        organismsArr.append({
                            'commonName' : newTag.organism.common_name,
                            'abbreviation' : newTag.organism.abbreviation,
                            'genus' : newTag.organism.genus,
                            'species' : newTag.organism.species,
                            'id' : newTag.organism.pk
                        })
            except DatabaseError as e:
                transaction.rollback()
                raise Errors.INTEGRITY_ERROR.setCustom(str(e))
        if description:
            image.description = description
            try:
                image.save()
            except DatabaseError as e:
                transaction.rollback()
                raise Errors.INTEGRITY_ERROR.setCustom(str(e))
            
        if altText:
            image.altText = altText
            try:
                image.save()
            except DatabaseError as e:
                transaction.rollback()
                raise Errors.INTEGRITY_ERROR.setCustom(str(e))
       
        metadata.limitFields(self.fields)
        
        if not organisms and organismField:
            for defTag in defTags:
                organisms.append({
                    'commonName' : defTag.organism.common_name,
                    'abbreviation' : defTag.organism.abbreviation,
                    'genus' : defTag.organism.genus,
                    'species' : defTag.organism.species,
                    'id' : defTag.organism.pk
                })
        # put in the information we care about
        metadata.put('organisms', organismsArr)
        metadata.put('description', image.description)
        metadata.put('altText', image.altText)
        metadata.put('uploadedBy', image.user.username)
        metadata.put('uploadDate', image.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('url', image.imageName.url)
        metadata.put('thumbnail', image.thumbnail.url)
        metadata.put('id', image.pk)
        
        return metadata
Ejemplo n.º 24
0
    def createGeneLink(self, tagKey, name=None,  allele=None, organismId=None, isKey=True):
        metadata = WebServiceObject()

        try:
            if isKey:
                tag = Tag.objects.get(pk__exact=tagKey)
            else:
                tag = tagKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_GROUP_KEY
        
        if not tag.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        try:
            feature = None
            if name and organismId:
                feature = Feature.objects.filter(name=name, organism=organismId)

            if not feature:
                error = "Could not find a feature with the parameters: "
                if name and organismId:
                    error += "name: " + name + ", organismId: " + organismId

                raise Errors.NO_MATCHING_FEATURE.setCustom(error)
            elif len(feature) > 1:
                error = "Multiple matches for parameters: "
                if name and organismId:
                    error += "name: " + name + ", organismId: " + organismId

                error += "\n\n Responses: \n\n"
                
                for f in feature:
                    error += "uniquename: " + f.uniquename + ", name: " + f.name + ", organism: " + f.organism.common_name + "\n\n"
                
                raise Errors.NO_MATCHING_FEATURE.setCustom(error)

            if allele:
                vID = None

                vID = Variation.objects.using('mgdb').filter(name__exact=allele)
                if not vID:
                    errorAllele = Errors.NO_MATCHING_ALLELE.setCustom(allele)
                    raise errorAllele

            geneLink = GeneLink(tag=tag, feature=feature[0], user=self.user, allele=allele)
            geneLink.save()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))
        
        # limit metadata return
        metadata.limitFields(self.fields)
            
        metadata.put('id', geneLink.pk)
        metadata.put('user', geneLink.user.username)
        metadata.put('tagId', geneLink.tag.pk)
        metadata.put('feature',
            LimitDict(self.fields, {
                'uniqueName' : geneLink.feature.uniquename,
                'name' : geneLink.feature.name,
                'allele': geneLink.allele,
                'organismId' : geneLink.feature.organism.organism_id
            })
        )
        
        return metadata
Ejemplo n.º 25
0
    def getNote(self, imageKey):
        metadata = WebServiceObject()

        try:
            pictureNotes = PictureNotes.objects.filter(
                picture__exact=imageKey).order_by('-dateCreated')[:1].get()
        except (ObjectDoesNotExist, ValueError):
            return metadata
        #except Exception:
        #    raise Errors.INTERNAL_ERROR

        metadata.limitFields(self.fields)

        metadata.put('pn_id', pictureNotes.pk)
        metadata.put('picture', pictureNotes.picture.pk)
        metadata.put('notes', pictureNotes.notes)
        metadata.put('user', pictureNotes.user.username)
        metadata.put('dateCreated',
                     pictureNotes.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))

        return metadata
Ejemplo n.º 26
0
    def updateTagGroup(self, tagGroupKey, name=None, isKey=True):
        metadata = WebServiceObject()
        try:
            if (isKey):
                tagGroup = TagGroup.objects.get(pk__exact=tagGroupKey)
            else:
                tagGroup = tagGroupKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_GROUP_KEY

        if not tagGroup.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        # update the name
        if name:
            tagGroup.name = name

        metadata.limitFields(self.fields)
        try:
            tagGroup.save()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        # add new tag to response for success
        metadata.put('id', tagGroup.pk)
        metadata.put('name', tagGroup.name)
        metadata.put('user', tagGroup.user.username)
        metadata.put('dateCreated',
                     tagGroup.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('lastModified',
                     tagGroup.lastModified.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('imageId', tagGroup.picture.pk)
        metadata.put('isPrivate', tagGroup.isPrivate)

        return metadata
Ejemplo n.º 27
0
    def updateTag(self, tagKey, points=None, name=None, color=None, isKey=True):
        metadata = WebServiceObject()
        try:
            if (isKey):
                tag = Tag.objects.get(pk__exact=tagKey)
            else:
                tag = tagKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_KEY

        if not tag.writePermissions(self.user):
            raise Errors.AUTHENTICATION
        
        # update the description
        if name:
            tag.name = name
        
        # update the color (ignores bad syntax)
        try:
            if color and len(color) == 3:
                tagColor = TagColor.objects.get_or_create(red=color[0], green=color[1], blue=color[2])[0]
                tag.color = tagColor
        except (ValueError, TypeError):
            raise Errors.INVALID_SYNTAX.setCustom('color')
        
        oldTagPoints = list(TagPoint.objects.filter(tag__exact=tag))
        
        # updates the tag points for this tag
        if points:
            # first we delete the old tag points (they aren't helpful anymore)
            # TODO: add Trash database for restoring accidental changes                    
            try:
                newTagPointModels = []
                # Save the new tag points
                # create the new tag points to put in the tag
                for counter, point in enumerate(points):
                    newTagPointModels.append(TagPoint(pointX=float(point['x']), pointY=float(point['y']) , rank=counter+1))
                    
            except (TypeError, KeyError, ValueError):
                raise Errors.INVALID_SYNTAX.setCustom('points')
        
        metadata.limitFields(self.fields)
        try:
            tag.save()
            if points:
                for newTagPoint in newTagPointModels:
                    newTagPoint.tag = tag
                    newTagPoint.save()
                
                for tagPoint in oldTagPoints:
                    tagPoint.delete()
                
                metadata.put('points', points)
            else:
                tagPoints = []
                for tagPoint in oldTagPoints:
                    tagPoints.append({
                        'x' : tagPoint.pointX, 
                        'y' : tagPoint.pointY
                    })
                metadata.put('points', tagPoints)
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))
        
        # add new tag to response for success
        metadata.put('id', tag.pk)
        metadata.put('user', tag.user)
        metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
        metadata.put('name', tag.name)
        
        return metadata
Ejemplo n.º 28
0
 def updateTagGroup(self, tagGroupKey, name=None, isKey=True):
     metadata = WebServiceObject()
     try:
         if (isKey):
             tagGroup = TagGroup.objects.get(pk__exact=tagGroupKey)
         else:
             tagGroup = tagGroupKey
     except (ObjectDoesNotExist, ValueError):
         raise Errors.INVALID_TAG_GROUP_KEY
     
     if not tagGroup.writePermissions(self.user):
         raise Errors.AUTHENTICATION
     
     # update the name
     if name:
         tagGroup.name = name
     
     metadata.limitFields(self.fields)
     try:
         tagGroup.save()
     except DatabaseError as e:
         transaction.rollback()
         raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     
     # add new tag to response for success
     metadata.put('id', tagGroup.pk)
     metadata.put('name', tagGroup.name)
     metadata.put('user', tagGroup.user.username)
     metadata.put('dateCreated', tagGroup.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))
     metadata.put('lastModified', tagGroup.lastModified.strftime("%Y-%m-%d %H:%M:%S"))
     metadata.put('imageId', tagGroup.picture.pk)
     metadata.put('isPrivate', tagGroup.isPrivate)
     
     return metadata
Ejemplo n.º 29
0
    def getTagGroup(self, tagGroupKey, isKey=True):
        metadata = WebServiceObject()

        try:
            if (isKey):
                tagGroup = TagGroup.objects.get(pk__exact=tagGroupKey)
            else:
                tagGroup = tagGroupKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_GROUP_KEY
        except Exception:
            raise Errors.INTERNAL_ERROR

        if not tagGroup.readPermissions(self.user):
            raise Errors.AUTHENTICATION

        metadata.limitFields(self.fields)

        metadata.put('id', tagGroup.pk)
        metadata.put('name', tagGroup.name)
        metadata.put('user', tagGroup.user.username)
        metadata.put('dateCreated',
                     tagGroup.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('lastModified',
                     tagGroup.lastModified.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('imageId', tagGroup.picture.pk)
        metadata.put('isPrivate', tagGroup.isPrivate)

        return metadata
Ejemplo n.º 30
0
 def deleteTag(self, tagKey, isKey=True):
     metadata = WebServiceObject()
     
     try:            
         if (isKey):
             tag = Tag.objects.get(pk__exact=tagKey)
         else:
             tag = tagKey
     except (ObjectDoesNotExist, ValueError):
         raise Errors.INVALID_GENE_LINK_KEY
     except Exception:
         raise Errors.INTERNAL_ERROR
         
     if not tag.writePermissions(self.user):
         raise Errors.AUTHENTICATION
     
     metadata.limitFields(self.fields)
     
     if metadata.allowsField('points'):
         tagPoints = TagPoint.objects.filter(tag__exact=tag)
         
         points = []
         
         for tagPoint in tagPoints:
             points.append({
                 'x' : tagPoint.pointX, 
                 'y' : tagPoint.pointY
             })
         
         metadata.put('points', points)
     
     metadata.put('id', tag.pk)
     metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
     metadata.put('name', tag.name)
     
     try:
         tag.delete()
     except DatabaseError as e:
         transaction.rollback()
         raise Errors.INTEGRITY_ERROR.setCustom(str(e))
Ejemplo n.º 31
0
 def createTag(self, tagGroupKey, points, name, color, isKey=True):
     metadata = WebServiceObject()
     tagPoints = []
     
     try:
         if isKey:
             tagGroup = TagGroup.objects.get(pk__exact=tagGroupKey)
         else:
             tagGroup = tagGroupKey
     except (ObjectDoesNotExist, ValueError):
             raise Errors.INVALID_TAG_GROUP_KEY
     
     if not tagGroup.writePermissions(self.user):
         raise Errors.AUTHENTICATION
         
     # create the new tag points to put in the tag
     try:
         for counter, point in enumerate(points):
             tagPoints.append(TagPoint(pointX=float(point['x']), pointY=float(point['y']) , rank=counter+1))
     except (TypeError, KeyError, ValueError):
         raise Errors.INVALID_SYNTAX.setCustom('points')
     
     try:
         # create new tag color
         try:
             if len(color) == 3:
                 tagColor = TagColor.objects.get_or_create(red=int(color[0]), green=int(color[1]), blue=int(color[2]))[0]
         except (ValueError, TypeError):
             raise Errors.INVALID_SYNTAX.setCustom('color')
         
         # start saving the new tag now that it has passed all tests
         tag = Tag(name=name, color=tagColor, group=tagGroup, user=self.user)
         tag.save()
         
         for tagPoint in tagPoints:
             tagPoint.tag = tag
             tagPoint.save()
     except DatabaseError as e:
         transaction.rollback()
         raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     
     # limit metadata return
     metadata.limitFields(self.fields)
     
     # add new tag to response for success
     metadata.put('id', tag.pk)
     metadata.put('user', tag.user.username)
     metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
     metadata.put('name', tag.name)
     metadata.put('points', points)
     
     return metadata
     
     
Ejemplo n.º 32
0
 def getGeneLink(self, geneLinkKey, isKey=True):
     metadata = WebServiceObject()
     
     try:            
         if isKey:
             geneLink = GeneLink.objects.get(pk__exact=geneLinkKey)
         else:
             geneLink = geneLinkKey
     except (ObjectDoesNotExist, ValueError):
         raise Errors.INVALID_GENE_LINK_KEY
     except Exception:
         raise Errors.INTERNAL_ERROR
     
     if not geneLink.readPermissions(self.user):
         raise Errors.AUTHENTICATION
     
     metadata.limitFields(self.fields)
         
     metadata.put('id', geneLink.pk)
     metadata.put('user', geneLink.user.username)
     metadata.put('tagId', geneLink.tag.pk)
     metadata.put('feature', 
         LimitDict(self.fields, {
             'uniqueName' : geneLink.feature.uniquename,
             'name': geneLink.feature.name,
             'organismId' : geneLink.feature.organism.organism_id
         })
     )
     return metadata
Ejemplo n.º 33
0
    def createTag(self, tagGroupKey, points, name, color, isKey=True):
        metadata = WebServiceObject()
        tagPoints = []

        try:
            if isKey:
                tagGroup = TagGroup.objects.get(pk__exact=tagGroupKey)
            else:
                tagGroup = tagGroupKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_GROUP_KEY

        if not tagGroup.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        # create the new tag points to put in the tag
        try:
            for counter, point in enumerate(points):
                tagPoints.append(
                    TagPoint(pointX=float(point['x']),
                             pointY=float(point['y']),
                             rank=counter + 1))
        except (TypeError, KeyError, ValueError):
            raise Errors.INVALID_SYNTAX.setCustom('points')

        try:
            # create new tag color
            try:
                if len(color) == 3:
                    tagColor = TagColor.objects.get_or_create(
                        red=int(color[0]),
                        green=int(color[1]),
                        blue=int(color[2]))[0]
            except (ValueError, TypeError):
                raise Errors.INVALID_SYNTAX.setCustom('color')

            # start saving the new tag now that it has passed all tests
            tag = Tag(name=name,
                      color=tagColor,
                      group=tagGroup,
                      user=self.user)
            tag.save()

            for tagPoint in tagPoints:
                tagPoint.tag = tag
                tagPoint.save()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        # limit metadata return
        metadata.limitFields(self.fields)

        # add new tag to response for success
        metadata.put('id', tag.pk)
        metadata.put('user', tag.user.username)
        metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
        metadata.put('name', tag.name)
        metadata.put('points', points)

        return metadata
Ejemplo n.º 34
0
 def createImageMetadata(self, image, description, altText, organisms, isKey=True):
     organismsArr = []
     metadata = WebServiceObject()
     
     if not (self.user and self.user.is_authenticated()):
         raise Errors.AUTHENTICATION
     filetype = imghdr.what(image.file)
     if not filetype or filetype not in set(['gif', 'tiff', 'jpeg', 'bmp', 'png']):
         raise Errors.INVALID_IMAGE_TYPE
     wrappedFile, thumbnailFile, filename, thumbnailName = handleUpload(image)
     
     
     if self.user.is_staff:
         upload = Picture(user=self.user, isPrivate=False, imageName=wrappedFile.file, thumbnail=thumbnailFile.file)
     else:
         upload = Picture(user=self.user, isPrivate=True, imageName=wrappedFile.file, thumbnail=thumbnailFile.file)            
     
     try:
         upload.save()
     except DatabaseError as e:
         transaction.rollback()
         os.remove(filename)
         os.remove(thumbnailName)
         raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     
     os.remove(filename)
     os.remove(thumbnailName)
     
     # now that image has been properly uploaded add the metadata to it
     
     organismField = not self.fields or 'organisms' in self.fields
     
     if organisms:
         newOrganisms = Organism.objects.filter(organism_id__in=organisms)
         newDefTags = []
         for newOrg in newOrganisms:
             newDefTags.append(PictureDefinitionTag(picture=upload, organism=newOrg))
         try:
             for newTag in newDefTags:
                 newTag.save()
                 if organismField:
                     organismsArr.append({
                         'commonName' : newTag.organism.common_name,
                         'abbreviation' : newTag.organism.abbreviation,
                         'genus' : newTag.organism.genus,
                         'species' : newTag.organism.species,
                         'id' : newTag.organism.pk
                     })
         except DatabaseError as e:
             transaction.rollback()
             raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     
     if description:
         upload.description = description
         try:
             upload.save()
         except DatabaseError as e:
             transaction.rollback()
             raise Errors.INTEGRITY_ERROR.setCustom(str(e))
         
     if altText:
         upload.altText = altText
         try:
             upload.save()
         except DatabaseError as e:
             transaction.rollback()
             raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     
     metadata.limitFields(self.fields)
     # put in the information we care about
     metadata.put('organisms', organismsArr)
     metadata.put('description', upload.description)
     metadata.put('altText', upload.altText)
     metadata.put('uploadedBy', upload.user.username)
     metadata.put('uploadDate', upload.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
     metadata.put('url', upload.imageName.url)
     metadata.put('thumbnail', upload.thumbnail.url)
     metadata.put('id', upload.pk)
         
     return metadata
Ejemplo n.º 35
0
    def updateTag(self,
                  tagKey,
                  points=None,
                  name=None,
                  color=None,
                  isKey=True):
        metadata = WebServiceObject()
        try:
            if (isKey):
                tag = Tag.objects.get(pk__exact=tagKey)
            else:
                tag = tagKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_KEY

        if not tag.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        # update the description
        if name:
            tag.name = name

        # update the color (ignores bad syntax)
        try:
            if color and len(color) == 3:
                tagColor = TagColor.objects.get_or_create(red=color[0],
                                                          green=color[1],
                                                          blue=color[2])[0]
                tag.color = tagColor
        except (ValueError, TypeError):
            raise Errors.INVALID_SYNTAX.setCustom('color')

        oldTagPoints = list(TagPoint.objects.filter(tag__exact=tag))

        # updates the tag points for this tag
        if points:
            # first we delete the old tag points (they aren't helpful anymore)
            # TODO: add Trash database for restoring accidental changes
            try:
                newTagPointModels = []
                # Save the new tag points
                # create the new tag points to put in the tag
                for counter, point in enumerate(points):
                    newTagPointModels.append(
                        TagPoint(pointX=float(point['x']),
                                 pointY=float(point['y']),
                                 rank=counter + 1))

            except (TypeError, KeyError, ValueError):
                raise Errors.INVALID_SYNTAX.setCustom('points')

        metadata.limitFields(self.fields)
        try:
            tag.save()
            if points:
                for newTagPoint in newTagPointModels:
                    newTagPoint.tag = tag
                    newTagPoint.save()

                for tagPoint in oldTagPoints:
                    tagPoint.delete()

                metadata.put('points', points)
            else:
                tagPoints = []
                for tagPoint in oldTagPoints:
                    tagPoints.append({
                        'x': tagPoint.pointX,
                        'y': tagPoint.pointY
                    })
                metadata.put('points', tagPoints)
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        # add new tag to response for success
        metadata.put('id', tag.pk)
        metadata.put('user', tag.user)
        metadata.put('color', [tag.color.red, tag.color.green, tag.color.blue])
        metadata.put('name', tag.name)

        return metadata
Ejemplo n.º 36
0
 def createTagGroup(self, imageKey, name, isKey=True):
     metadata = WebServiceObject()
     
     try:
         if isKey:
             image = Picture.objects.get(pk__exact=imageKey)
         else:
             image = imageKey
     except (ObjectDoesNotExist, ValueError):
         raise Errors.INVALID_IMAGE_KEY
     
     if not image.writePermissions(self.user):
         raise Errors.AUTHENTICATION
     
     # start saving the new tag now that it has passed all tests
     tagGroup = TagGroup(name=name, picture=image, user=self.user)
     try:
         tagGroup.save()
     except DatabaseError as e:
         transaction.rollback()
         raise Errors.INTEGRITY_ERROR.setCustom(str(e))
     # limit metadata return
     metadata.limitFields(self.fields)
     
     # add new tag to response for success
     metadata.put('id', tagGroup.pk)
     metadata.put('name', tagGroup.name)
     metadata.put('user', tagGroup.user.username)
     metadata.put('dateCreated', tagGroup.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))
     metadata.put('lastModified', tagGroup.lastModified.strftime("%Y-%m-%d %H:%M:%S"))
     metadata.put('imageId', tagGroup.picture.pk)
     metadata.put('isPrivate', tagGroup.isPrivate)
     
     return metadata
     
     
Ejemplo n.º 37
0
    def getImageMetadata(self, imageKey, isKey=True):
        organisms = []
        metadata = WebServiceObject()

        try:
            if (isKey):
                image = Picture.objects.get(pk__exact=imageKey)
            else:
                image = imageKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY

        if not image.readPermissions(self.user):
            raise Errors.AUTHENTICATION

        if not self.fields or 'organisms' in self.fields:
            defTags = PictureDefinitionTag.objects.filter(picture__exact=image)

            for tag in defTags:
                organisms.append({
                    'commonName': tag.organism.common_name,
                    'abbreviation': tag.organism.abbreviation,
                    'genus': tag.organism.genus,
                    'species': tag.organism.species,
                    'id': tag.organism.pk
                })

        metadata.limitFields(self.fields)

        # put in the information we care about
        metadata.put('organisms', organisms)
        metadata.put('description', image.description)
        metadata.put('altText', image.altText)
        metadata.put('uploadedBy', image.user.username)
        metadata.put('uploadDate',
                     image.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('url', image.imageName.url)
        metadata.put('thumbnail', image.thumbnail.url)
        metadata.put('id', image.pk)

        # add to recently viewed images if there is a user
        if self.user and self.user.is_authenticated():
            RecentlyViewedPicture.objects.get_or_create(
                user=self.user, picture=image)[0].save()

        return metadata
Ejemplo n.º 38
0
    def deleteImage(self, imageKey, isKey=True):
        organisms = []
        metadata = WebServiceObject()
        
        try:
            if isKey:
                image = Picture.objects.get(pk__exact=imageKey) 
            else:
                image = imageKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY
            
                
        if not image.writePermissions(self.user):
            raise Errors.AUTHENTICATION
        
        if not self.fields or 'organisms' in self.fields:
            defTags = PictureDefinitionTag.objects.filter(picture__exact=image)
            
            for tag in defTags:
                try:
                    organisms.append({
                        'commonName' : tag.organism.common_name,
                        'abbreviation' : tag.organism.abbreviation,
                        'genus' : tag.organism.genus,
                        'species' : tag.organism.species,
                        'id' : tag.organism.pk
                    })
                except ObjectDoesNotExist:
                    None
        
        metadata.limitFields(self.fields)

        # put in the information we care about
        metadata.put('organisms', organisms)
        metadata.put('description', image.description)
        metadata.put('altText', image.altText)
        metadata.put('uploadedBy', image.user.username)
        metadata.put('uploadDate', image.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('url', image.imageName.url)
        metadata.put('thumbnail', image.thumbnail.url)
        metadata.put('id', image.pk)
        
        try:
            image.delete()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))
        
        return metadata
Ejemplo n.º 39
0
    def deleteTagGroup(self, tagGroupKey, isKey=True):
        metadata = WebServiceObject()

        try:
            if isKey:
                tagGroup = TagGroup.objects.get(pk__exact=tagGroupKey)
            else:
                tagGroup = tagGroupKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_TAG_GROUP_KEY
        except Exception:
            raise Errors.INTERNAL_ERROR

        if not tagGroup.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        metadata.limitFields(self.fields)

        # add new tag to response for success
        metadata.put("id", tagGroup.pk)
        metadata.put("name", tagGroup.name)
        metadata.put("dateCreated", tagGroup.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put("lastModified", tagGroup.lastModified.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put("imageId", tagGroup.picture.pk)

        try:
            tagGroup.delete()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        return metadata
Ejemplo n.º 40
0
    def getImageMetadata(self, imageKey, isKey=True):
        organisms = []
        metadata = WebServiceObject()
        
        try:
            if (isKey):
                image = Picture.objects.get(pk__exact=imageKey) 
            else:
                image = imageKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY
            
        if not image.readPermissions(self.user):
            raise Errors.AUTHENTICATION
        
        if not self.fields or 'organisms' in self.fields:
            defTags = PictureDefinitionTag.objects.filter(picture__exact=image)
            
            for tag in defTags:
                organisms.append({
                    'commonName' : tag.organism.common_name,
                    'abbreviation' : tag.organism.abbreviation,
                    'genus' : tag.organism.genus,
                    'species' : tag.organism.species,
                    'id' : tag.organism.pk
                })
        
        metadata.limitFields(self.fields)

        # put in the information we care about
        metadata.put('organisms', organisms)
        metadata.put('description', image.description)
        metadata.put('altText', image.altText)
        metadata.put('uploadedBy', image.user.username)
        metadata.put('uploadDate', image.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('url', image.imageName.url)
        metadata.put('thumbnail', image.thumbnail.url)
        metadata.put('id', image.pk)
        
        # add to recently viewed images if there is a user
        if self.user and self.user.is_authenticated():
            RecentlyViewedPicture.objects.get_or_create(user=self.user, picture=image)[0].save()
        
        return metadata
Ejemplo n.º 41
0
    def getImageMetadata(self, imageKey, isKey=True):
        # TODO: getImageMetadata() should be refactorized because it is used for all image loading parts
        #  including image list even thumbnail image. It potentially has unnecessary database queries.

        organisms = []
        geneIDs = []
        metadata = WebServiceObject()

        try:
            if (isKey):
                image = Picture.objects.get(pk__exact=imageKey)
            else:
                image = imageKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY

        # Get gene information
        geneSymbol = None
        geneName = None
        if image is not None:
            # Gene ID
            pictureGIDs = PictureGeneID.objects.filter(picture__exact=image)
            for picGID in pictureGIDs:
                geneIDs.append({
                    'geneID': picGID.gene_id,
                    'version': picGID.version
                })

            pictureMbs = PictureMgdb.objects.filter(picture__exact=image)
            for pMb in pictureMbs:
                geneSymbol = pMb.locus_name
                geneName = pMb.locus_full_name
                break

        if not image.readPermissions(self.user):
            raise Errors.AUTHENTICATION

        if not self.fields or 'organisms' in self.fields:
            defTags = PictureDefinitionTag.objects.filter(picture__exact=image)

            for tag in defTags:
                organisms.append({
                    'commonName': tag.organism.common_name,
                    'abbreviation': tag.organism.abbreviation,
                    'genus': tag.organism.genus,
                    'species': tag.organism.species,
                    'id': tag.organism.pk
                })

        # Get all imageID for imageName
        images = Picture.objects.filter(imageName__exact=image.imageName)

        # Get Image Notes Information
        notes_id = ''
        notes = ''
        notesBy = ''

        pictureNotesAPI = NotesAPI(self.user)
        for imageID in images:
            pictureNotes = pictureNotesAPI.getNote(imageID).getObject()
            if pictureNotes:
                notes_id = pictureNotes['pn_id']
                notes = pictureNotes['notes']
                notesBy = pictureNotes['user']
                break

        # Get QTL information
        qtls_id = ''
        qtl = ''
        pictureQtlAPI = QtlAPI(self.user)
        for imageID in images:
            pictureQtl = pictureQtlAPI.getQtl(imageID).getObject()
            if pictureQtl:
                qtls_id = pictureQtl['pq_id']
                qtl = pictureQtl['qtl']
                break

        metadata.limitFields(self.fields)

        # put in the information we care about
        metadata.put('organisms', organisms)
        metadata.put('description', image.description)
        metadata.put('altText', image.altText)
        metadata.put('uploadedBy', image.user.username)
        metadata.put('uploadDate',
                     image.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('url', image.imageName.url)
        metadata.put('thumbnail', image.thumbnail.url)
        metadata.put('id', image.pk)
        metadata.put('geneIDs', geneIDs)
        metadata.put('geneSymbol', geneSymbol)
        metadata.put('geneName', geneName)
        metadata.put('notes_id', notes_id)
        metadata.put('notes', notes)
        metadata.put('notesBy', notesBy)
        metadata.put('qtls_id', qtls_id)
        metadata.put('qtl', qtl)

        return metadata
Ejemplo n.º 42
0
    def getQtl(self, imageKey):
        metadata = WebServiceObject()

        try:
            pictureQtl = PictureQtl.objects.filter(
                picture__exact=imageKey).order_by('-dateCreated')[:1].get()
        except (ObjectDoesNotExist, ValueError):
            return metadata

        metadata.limitFields(self.fields)

        metadata.put('pq_id', pictureQtl.pk)
        metadata.put('picture', pictureQtl.picture.pk)
        metadata.put('qtl', pictureQtl.qtl)
        metadata.put('user', pictureQtl.user.username)
        metadata.put('dateCreated',
                     pictureQtl.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))

        return metadata
Ejemplo n.º 43
0
    def addQtl(self, qtl, pq_id, imageKey):
        metadata = WebServiceObject()

        print 'test 1'

        # get picture instance with imageKey
        try:
            image = Picture.objects.get(pk__exact=imageKey)
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY

        if not self.user:
            raise Errors.NO_USER_KEY
        else:
            userID = self.user

        try:
            # save the new note
            if pq_id:
                # update
                pictureQtl = PictureQtl.objects.get(pk__exact=pq_id)
                if pictureQtl:
                    pictureQtl.qtl = qtl
                    pictureQtl.picture = image
                    pictureQtl.user = userID
                    pictureQtl.save()
                else:
                    # error
                    print 'Error: no PictureQtl.pk found!'
            else:
                # add new
                pictureQtl = PictureQtl(qtl=qtl, picture=image, user=userID)
                print 'test: trying store qtl.'
                pictureQtl.save()
                print 'test: qtl saved.'

        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        # limit metadata return
        metadata.limitFields(self.fields)

        # add new tag to response for success
        metadata.put('pq_id', pictureQtl.pk)
        metadata.put('picture', pictureQtl.picture.pk)
        metadata.put('qtl', pictureQtl.qtl)
        metadata.put('user', pictureQtl.user.username)
        metadata.put('dateCreated',
                     pictureQtl.dateCreated.strftime("%Y-%m-%d %H:%M:%S"))

        return metadata
Ejemplo n.º 44
0
    def deleteImage(self, imageKey, isKey=True):
        organisms = []
        metadata = WebServiceObject()

        try:
            if isKey:
                image = Picture.objects.get(pk__exact=imageKey)
            else:
                image = imageKey
        except (ObjectDoesNotExist, ValueError):
            raise Errors.INVALID_IMAGE_KEY

        if not image.writePermissions(self.user):
            raise Errors.AUTHENTICATION

        if not self.fields or 'organisms' in self.fields:
            defTags = PictureDefinitionTag.objects.filter(picture__exact=image)

            for tag in defTags:
                try:
                    organisms.append({
                        'commonName': tag.organism.common_name,
                        'abbreviation': tag.organism.abbreviation,
                        'genus': tag.organism.genus,
                        'species': tag.organism.species,
                        'id': tag.organism.pk
                    })
                except ObjectDoesNotExist:
                    None

        metadata.limitFields(self.fields)

        # put in the information we care about
        metadata.put('organisms', organisms)
        metadata.put('description', image.description)
        metadata.put('altText', image.altText)
        metadata.put('uploadedBy', image.user.username)
        metadata.put('uploadDate',
                     image.uploadDate.strftime("%Y-%m-%d %H:%M:%S"))
        metadata.put('url', image.imageName.url)
        metadata.put('thumbnail', image.thumbnail.url)
        metadata.put('id', image.pk)

        try:
            image.delete()
        except DatabaseError as e:
            transaction.rollback()
            raise Errors.INTEGRITY_ERROR.setCustom(str(e))

        return metadata