Example #1
0
def updateAllUuids(planDict):
    planDict.uuid = makeUuid()
    for element in planDict.sequence:
        element.uuid = makeUuid()
        if hasattr(element, 'sequence'):
            for child in element.sequence:
                if hasattr(child, 'uuid'):
                    child.uuid = makeUuid()
    return planDict
Example #2
0
def updateAllUuids(planDict):
    planDict.uuid = makeUuid()
    for element in planDict.sequence:
        element.uuid = makeUuid()
        if hasattr(element, 'sequence'):
            for child in element.sequence:
                if hasattr(child, 'uuid'):
                    child.uuid = makeUuid()
    return planDict
Example #3
0
    def extractFromJson(self,
                        overWriteDateModified=True,
                        overWriteUuid=True,
                        request=None):
        if overWriteUuid:
            if not self.uuid:
                self.uuid = makeUuid()
                self.jsonPlan.uuid = self.uuid
            self.jsonPlan.serverId = self.pk
        if overWriteDateModified:
            self.jsonPlan.dateModified = (datetime.datetime.now(
                pytz.utc).replace(microsecond=0).isoformat())
            self.jsonPlan.dateModified = self.jsonPlan.dateModified[:-6] + 'Z'

        self.name = self.jsonPlan.name
        self.jsonPlan.url = self.get_absolute_url()
        self.jsonPlan.serverId = self.pk
        self.dateModified = dateparser(
            self.jsonPlan.dateModified).replace(tzinfo=pytz.utc)
        plannerUsers = User.objects.filter(username=self.jsonPlan.creator)
        if plannerUsers:
            self.creator = plannerUsers[0]
        else:
            self.creator = None

        # fill in stats
        try:
            exporter = statsPlanExporter.StatsPlanExporter()
            #             print ' about to do stats'
            stats = exporter.exportDbPlan(self, request)
            for f in ('numStations', 'numSegments', 'numCommands',
                      'lengthMeters', 'estimatedDurationSeconds'):
                setattr(self, f, stats[f])
            self.stats.numCommandsByType = stats["numCommandsByType"]
            self.summary = statsPlanExporter.getSummary(stats)
        except:
            logging.warning(
                'extractFromJson: could not extract stats from plan %s',
                self.uuid)
            raise  # FIX
        return self
Example #4
0
    def extractFromJson(self, overWriteDateModified=True, overWriteUuid=True):
        if overWriteUuid:
            if not self.uuid:
                self.uuid = makeUuid()
                self.jsonPlan.uuid = self.uuid
            self.jsonPlan.serverId = self.pk
        if overWriteDateModified:
            self.jsonPlan.dateModified = (datetime.datetime
                                          .now(pytz.utc)
                                          .replace(microsecond=0)
                                          .isoformat())
            self.jsonPlan.dateModified = self.jsonPlan.dateModified[:-6]+'Z'

        self.name = self.jsonPlan.name
        self.jsonPlan.url = self.get_absolute_url()
        self.jsonPlan.serverId = self.pk
        self.dateModified = dateparser(self.jsonPlan.dateModified).replace(tzinfo=pytz.utc)
        plannerUsers = User.objects.filter(username=self.jsonPlan.creator)
        if plannerUsers:
            self.creator = plannerUsers[0]
        else:
            self.creator = None

        # fill in stats
        try:
            exporter = statsPlanExporter.StatsPlanExporter()
#             print ' about to do stats'
            stats = exporter.exportDbPlan(self)
            for f in ('numStations', 'numSegments', 'numCommands', 'lengthMeters', 'estimatedDurationSeconds'):
                setattr(self, f, stats[f])
            self.stats.numCommandsByType = stats["numCommandsByType"]
            self.summary = statsPlanExporter.getSummary(stats)
        except:
            logging.warning('extractFromJson: could not extract stats from plan %s',
                            self.uuid)
            raise  # FIX
        return self
Example #5
0
    def uploadImage(self, request, userName):
        author = User.objects.get(username=userName)
        if request.method == 'POST':
            print >>sys.stderr, 'upload image start'
            form = UploadImageForm(request.POST, request.FILES)
            print >>sys.stderr, 'FILES:', request.FILES.keys()
            if form.is_valid():
                incoming = request.FILES['photo']

                # store image data in temp file
                fd, tempStorePath = tempfile.mkstemp('-uploadImage.jpg')
                os.close(fd)
                storeFile = file(tempStorePath, 'wb')
                for chunk in incoming.chunks():
                    storeFile.write(chunk)
                storeFile.close()
                print >>sys.stderr, 'upload: saved image data to temp file:', tempStorePath

                # create image db record
                uuid = form.cleaned_data.setdefault('uuid', makeUuid())
                form.cleaned_data['name'] = incoming.name
                form.cleaned_data['author'] = author
                uuidMatches = self.defaultImageModel.objects.filter(uuid=uuid)
                sameUuid = (uuidMatches.count() > 0)
                if sameUuid:
                    # if the incoming uuid matches an existing uuid, this is
                    # either (1) a duplicate upload of the same image or (2)
                    # the next higher resolution level in an incremental
                    # upload.
                    img = uuidMatches.get()
                    print >>sys.stderr, 'upload: photo %s with same uuid %s posted' % (img.name, img.uuid)
                    newVersion = img.version + 1
                else:
                    # create Image db record
                    img = self.defaultImageModel()
                    img.readImportVals(storePath=tempStorePath,
                                       uploadImageFormData=form.cleaned_data)

                    # set version
                    newVersion = 0

                # check the new image file on disk to get the dimensions
                im = PIL.Image.open(tempStorePath, 'r')
                newRes = im.size
                del im
                    
                if sameUuid:
                    oldRes = (img.widthPixels, img.heightPixels)
                    if newRes > oldRes:
                        print >>sys.stderr, 'upload: resolution increased from %d to %d' % (oldRes[0], newRes[0])
                        img.widthPixels, img.heightPixels = newRes
                        img.processed = False
                    else:
                        print >>sys.stderr, 'upload: ignoring dupe, but telling the client it was received so it stops trying'
                else:
                    img.widthPixels, img.heightPixels = newRes

                if not img.processed:
                    # generate thumbnails and any other processing
                    # (better to do this part in the background, but we
                    # don't have that set up yet)
                    img.version = newVersion
                    # make sure the image gets an id if it doesn't already have one --
                    # the id will be used in process() to calculate the storage path
                    img.save()
                    img.process(importFile=tempStorePath)
                    img.save()

                # after import by process(), can delete redundant temp copy
                os.unlink(tempStorePath)

                print >>sys.stderr, 'upload image end'

                # swfupload requires non-empty response text.
                # also added a text pattern (in html comment) for clients to check against to make sure
                # photo has actually arrived in share.  we also put a matching line in the error log so we
                # never again run into the issue that the phone thinks it successfully uploaded but there
                # is no record of the http post on the server.
                print >>sys.stderr, 'GEOCAM_SHARE_POSTED %s' % img.name
                return HttpResponse('file posted <!--\nGEOCAM_SHARE_POSTED %s\n-->' % img.name)

            else:
                print >>sys.stderr, "form is invalid"
                print >>sys.stderr, "form errors: ", form._errors
                userAgent = request.META.get('HTTP_USER_AGENT', '')
                # swfupload user can't see errors in form response, best return an error code
                if 'Flash' in userAgent:
                    return http.HttpResponseBadRequest('<h1>400 Bad Request</h1>')
        else:
            form = UploadImageForm()
            #print 'form:', form
        resp = render_to_response('upload.html',
                                  dict(form=form,
                                       author=author,
                                       ),
                                  context_instance=RequestContext(request))
        print >>sys.stderr, 'upload image end'
        return resp
Example #6
0
    def uploadImage(self, request, userName):
        author = User.objects.get(username=userName)
        if request.method == 'POST':
            print >> sys.stderr, 'upload image start'
            form = UploadImageForm(request.POST, request.FILES)
            print >> sys.stderr, 'FILES:', request.FILES.keys()
            if form.is_valid():
                incoming = request.FILES['photo']

                # store image data in temp file
                fd, tempStorePath = tempfile.mkstemp('-uploadImage.jpg')
                os.close(fd)
                storeFile = file(tempStorePath, 'wb')
                for chunk in incoming.chunks():
                    storeFile.write(chunk)
                storeFile.close()
                print >> sys.stderr, 'upload: saved image data to temp file:', tempStorePath

                # create image db record
                uuid = form.cleaned_data.setdefault('uuid', makeUuid())
                form.cleaned_data['name'] = incoming.name
                form.cleaned_data['author'] = author
                uuidMatches = self.defaultImageModel.objects.filter(uuid=uuid)
                sameUuid = (uuidMatches.count() > 0)
                if sameUuid:
                    # if the incoming uuid matches an existing uuid, this is
                    # either (1) a duplicate upload of the same image or (2)
                    # the next higher resolution level in an incremental
                    # upload.
                    img = uuidMatches.get()
                    print >> sys.stderr, 'upload: photo %s with same uuid %s posted' % (
                        img.name, img.uuid)
                    newVersion = img.version + 1
                else:
                    # create Image db record
                    img = self.defaultImageModel()
                    img.readImportVals(storePath=tempStorePath,
                                       uploadImageFormData=form.cleaned_data)

                    # set version
                    newVersion = 0

                # check the new image file on disk to get the dimensions
                im = PIL.Image.open(tempStorePath, 'r')
                newRes = im.size
                del im

                if sameUuid:
                    oldRes = (img.widthPixels, img.heightPixels)
                    if newRes > oldRes:
                        print >> sys.stderr, 'upload: resolution increased from %d to %d' % (
                            oldRes[0], newRes[0])
                        img.widthPixels, img.heightPixels = newRes
                        img.processed = False
                    else:
                        print >> sys.stderr, 'upload: ignoring dupe, but telling the client it was received so it stops trying'
                else:
                    img.widthPixels, img.heightPixels = newRes

                if not img.processed:
                    # generate thumbnails and any other processing
                    # (better to do this part in the background, but we
                    # don't have that set up yet)
                    img.version = newVersion
                    # make sure the image gets an id if it doesn't already have one --
                    # the id will be used in process() to calculate the storage path
                    img.save()
                    img.process(importFile=tempStorePath)
                    img.save()

                # after import by process(), can delete redundant temp copy
                os.unlink(tempStorePath)

                print >> sys.stderr, 'upload image end'

                # swfupload requires non-empty response text.
                # also added a text pattern (in html comment) for clients to check against to make sure
                # photo has actually arrived in share.  we also put a matching line in the error log so we
                # never again run into the issue that the phone thinks it successfully uploaded but there
                # is no record of the http post on the server.
                print >> sys.stderr, 'GEOCAM_SHARE_POSTED %s' % img.name
                return HttpResponse(
                    'file posted <!--\nGEOCAM_SHARE_POSTED %s\n-->' % img.name)

            else:
                print >> sys.stderr, "form is invalid"
                print >> sys.stderr, "form errors: ", form._errors
                userAgent = request.META.get('HTTP_USER_AGENT', '')
                # swfupload user can't see errors in form response, best return an error code
                if 'Flash' in userAgent:
                    return http.HttpResponseBadRequest(
                        '<h1>400 Bad Request</h1>')
        else:
            form = UploadImageForm()
            #print 'form:', form
        resp = render_to_response('upload.html',
                                  dict(
                                      form=form,
                                      author=author,
                                  ),
                                  context_instance=RequestContext(request))
        print >> sys.stderr, 'upload image end'
        return resp