Exemple #1
0
    def uploadTrack(self, request, authorName):
        author = User.objects.get(username=authorName)
        if request.method == 'POST':
            print >>sys.stderr, 'upload track start'
            form = UploadTrackForm(request.POST, request.FILES)
            print >>sys.stderr, 'FILES:', request.FILES.keys()
            if form.is_valid():
                uuid = form.cleaned_data['uuid'] or makeUuid()
                if Track.objects.filter(uuid=uuid).count():
                    print >>sys.stderr, 'upload: track with same uuid %s posted' % img.uuid
                    print >>sys.stderr, 'upload: ignoring dupe, but telling the client it was received so it stops trying'
                else:
                    track = form.save(commit=False)
                    track.uuid = uuid
                    track.gpx = request.FILES['gpxFile'].read()
                    track.author = author
                    if track.icon == '':
                        track.icon = Track._meta.get_field('icon').default
                    try:
                        track.process()
                    except EmptyTrackError:
                        print >>sys.stderr, 'upload: ignoring empty track, but telling the client it was received so it stops trying'
                    else:
                        track.save()

                # return a pattern for clients to check for to ensure
                # the data was actually posted.  in bad network conditions
                # we've seen clients get back bogus empty '200 ok' responses
                # so this check is important to make sure they keep trying.
                posted = 'GEOCAM_SHARE_POSTED %s' % track.uuid
                print >>sys.stderr, posted
                continueUrl = form.cleaned_data['referrer'] or settings.SCRIPT_NAME
                result = render_to_response('trackUploadDone.html',
                                            dict(posted=posted,
                                                 continueUrl=continueUrl),
                                            context_instance=RequestContext(request))
                print >>sys.stderr, 'upload track end'
                return result
            else:
                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 = UploadTrackForm(initial=dict(referrer=request.META.get('HTTP_REFERER'),
                                                uuid=''))
            #print 'form:', form
        resp = render_to_response('trackUpload.html',
                                  dict(form=form,
                                       authorName=authorName),
                                  context_instance=RequestContext(request))
        print >>sys.stderr, 'upload image end'
        return resp
Exemple #2
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