Exemple #1
0
def upload_file(request):
    if request.method != 'POST':
        return error(request, 'Wrong HTTP method!')

    filename = set_filename(request)
    path = file_path()
    print(filename)
    print(path)
    if not os.path.exists(path):
        try:
            os.makedirs(path)
        except OSError:
            return error(request, 'Can\'t create upload directory!')

    filename = os.path.basename(filename)
    print(filename)
    temp_file = SimpleUploadedFile(filename,
                                   request.read(),
                                   content_type='text/xml')
    print(temp_file)
    with open(os.path.join(path, filename), 'wb') as f:
        for chunk in temp_file.chunks():
            f.write(chunk)

    return success(request)
Exemple #2
0
def upload_file(request):
    if request.method != 'POST':
        return error(request, 'Wrong HTTP method!')
    try:
        filename = request.GET['filename']
    except KeyError:
        return error(request, 'Need a filename param!')
    if not os.path.exists(settings.CML_UPLOAD_ROOT):
        try:
            os.makedirs(settings.CML_UPLOAD_ROOT)
        except OSError:
            return error(request, 'Can\'t create upload directory!')
    filename = os.path.basename(filename)
    temp_file = SimpleUploadedFile(filename, request.read(), content_type='text/xml')
    with open(os.path.join(settings.CML_UPLOAD_ROOT, filename), 'wb') as f:
        for chunk in temp_file.chunks():
            f.write(chunk)
    return success(request)
Exemple #3
0
    def catalog_file(self, request, *args, **kwargs):
        """
        Выгрузка файлов на сайт.
        """
        try:
            filename = os.path.basename(request.GET['filename'])
        except KeyError:
            return self.failure('Filename param required')

        if not os.path.exists(odinass_settings.UPLOAD_ROOT):
            try:
                os.makedirs(odinass_settings.UPLOAD_ROOT)
            except OSError:
                return self.failure('Can\'t create upload directory')

        temp_file = SimpleUploadedFile(filename,
                                       request.read(),
                                       content_type='text/xml')

        with open(os.path.join(odinass_settings.UPLOAD_ROOT, filename),
                  'ab') as f:
            for chunk in temp_file.chunks():
                f.write(chunk)
        return self.success()
Exemple #4
0
    def _save_FIELD_file(self, field, filename, raw_field, save=True):
        # Create the upload directory if it doesn't already exist
        directory = os.path.join(settings.MEDIA_ROOT,
                                 field.get_directory_name())
        if not os.path.exists(directory):
            os.makedirs(directory)
        elif not os.path.isdir(directory):
            raise IOError('%s exists and is not a directory' % directory)

        # Check for old-style usage (files-as-dictionaries). Warn here first
        # since there are multiple locations where we need to support both new
        # and old usage.
        if isinstance(raw_field, dict):
            import warnings
            warnings.warn(
                message=
                "Representing uploaded files as dictionaries is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.",
                category=DeprecationWarning,
                stacklevel=2)
            from django.core.files.uploadedfile import SimpleUploadedFile
            raw_field = SimpleUploadedFile.from_dict(raw_field)

        elif isinstance(raw_field, str):
            import warnings
            warnings.warn(
                message=
                "Representing uploaded files as strings is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.",
                category=DeprecationWarning,
                stacklevel=2)
            from django.core.files.uploadedfile import SimpleUploadedFile
            raw_field = SimpleUploadedFile(filename, raw_field)

        if filename is None:
            filename = raw_field.file_name

        filename = field.get_filename(filename)

        # If the filename already exists, keep adding an underscore to the name
        # of the file until the filename doesn't exist.
        while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)):
            try:
                dot_index = filename.rindex('.')
            except ValueError:  # filename has no dot.
                filename += '_'
            else:
                filename = filename[:dot_index] + '_' + filename[dot_index:]

        # Save the file name on the object and write the file to disk.
        setattr(self, field.attname, filename)
        full_filename = self._get_FIELD_filename(field)
        if hasattr(raw_field, 'temporary_file_path'):
            # This file has a file path that we can move.
            raw_field.close()
            file_move_safe(raw_field.temporary_file_path(), full_filename)
        else:
            # This is a normal uploadedfile that we can stream.
            fp = open(full_filename, 'wb')
            locks.lock(fp, locks.LOCK_EX)
            for chunk in raw_field.chunks():
                fp.write(chunk)
            locks.unlock(fp)
            fp.close()

        # Save the width and/or height, if applicable.
        if isinstance(field, ImageField) and \
                (field.width_field or field.height_field):
            from django.utils.images import get_image_dimensions
            width, height = get_image_dimensions(full_filename)
            if field.width_field:
                setattr(self, field.width_field, width)
            if field.height_field:
                setattr(self, field.height_field, height)

        # Save the object because it has changed, unless save is False.
        if save:
            self.save()
Exemple #5
0
    def _save_FIELD_file(self, field, filename, raw_field, save=True):
        # Create the upload directory if it doesn't already exist
        directory = os.path.join(settings.MEDIA_ROOT, field.get_directory_name())
        if not os.path.exists(directory):
            os.makedirs(directory)
        elif not os.path.isdir(directory):
            raise IOError('%s exists and is not a directory' % directory)        

        # Check for old-style usage (files-as-dictionaries). Warn here first
        # since there are multiple locations where we need to support both new
        # and old usage.
        if isinstance(raw_field, dict):
            import warnings
            warnings.warn(
                message = "Representing uploaded files as dictionaries is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.",
                category = DeprecationWarning,
                stacklevel = 2
            )
            from django.core.files.uploadedfile import SimpleUploadedFile
            raw_field = SimpleUploadedFile.from_dict(raw_field)

        elif isinstance(raw_field, str):
            import warnings
            warnings.warn(
                message = "Representing uploaded files as strings is deprecated. Use django.core.files.uploadedfile.SimpleUploadedFile instead.",
                category = DeprecationWarning,
                stacklevel = 2
            )
            from django.core.files.uploadedfile import SimpleUploadedFile
            raw_field = SimpleUploadedFile(filename, raw_field)

        if filename is None:
            filename = raw_field.file_name

        filename = field.get_filename(filename)

        # If the filename already exists, keep adding an underscore to the name
        # of the file until the filename doesn't exist.
        while os.path.exists(os.path.join(settings.MEDIA_ROOT, filename)):
            try:
                dot_index = filename.rindex('.')
            except ValueError: # filename has no dot.
                filename += '_'
            else:
                filename = filename[:dot_index] + '_' + filename[dot_index:]

        # Save the file name on the object and write the file to disk.
        setattr(self, field.attname, filename)
        full_filename = self._get_FIELD_filename(field)
        if hasattr(raw_field, 'temporary_file_path'):
            # This file has a file path that we can move.
            raw_field.close()
            file_move_safe(raw_field.temporary_file_path(), full_filename)
        else:
            # This is a normal uploadedfile that we can stream.
            fp = open(full_filename, 'wb')
            locks.lock(fp, locks.LOCK_EX)
            for chunk in raw_field.chunks():
                fp.write(chunk)
            locks.unlock(fp)
            fp.close()

        # Save the width and/or height, if applicable.
        if isinstance(field, ImageField) and \
                (field.width_field or field.height_field):
            from django.utils.images import get_image_dimensions
            width, height = get_image_dimensions(full_filename)
            if field.width_field:
                setattr(self, field.width_field, width)
            if field.height_field:
                setattr(self, field.height_field, height)

        # Save the object because it has changed, unless save is False.
        if save:
            self.save()
Exemple #6
0
def upload_photo(request):
    """ Remotely uploads a photo and returns a JSON TempPhoto object

    GET Parameters:
        qqfile:     Name of the file being uploaded, if the browser supports XHR
                    uploads this will apear in request.raw_post_data
        spec:       Name of the ImageSpec to proess this photo with.  Make sure
                    the ImageSpec actually exists in photos.imagespecs otherwise
                    bad things will happen.

    Returns:
        {
            'status':   1 if successful, 0 otherwise
            'id':       ID of the newly created TempPhoto object,
            'url':      URL to display the imagespec-processed photo requested,
            'message':  Error message, only if status==0,
        }
    """
    
    
    #Browser detection
    browser = None
    if 'MSIE' in request.META['HTTP_USER_AGENT']:
        browser = 'ie'
    elif 'Firefox/3.0' in request.META['HTTP_USER_AGENT']:
        browser = 'ff3'
    
    if browser in ['ff3', 'ie']:
        mimetype="text/html"
    else:
        mimetype="application/json"
    
    if request.method == 'POST':
        
        if browser in ['ff3', 'ie']:
            filename = request.FILES['qqfile']._name
        else:
            filename = request.GET.get('qqfile', None)
        
        if filename:
            # TODO: SimpleUploadedFile is the in-memory upload handler.  Is this
            # going to kill our server with large files?
            if browser in ['ff3', 'ie']:
                file = request.FILES['qqfile']
            else:
                file = SimpleUploadedFile(filename, request.raw_post_data)
                
            user_id = request.POST.get('user_id', None)
            user = request.user
            if user_id:
                try:
                    user = User.objects.get(id=user_id)
                except User.DoesNotExist:
                    response = {
                        'status': 0,
                        'message': "User does not exit: %s" % user_id,
                    }
                    return HttpResponse(json.dumps(response), mimetype=mimetype)
            
            user_id = user.id
            if user.is_anonymous():
                user = None
                user_id = 'site'
            
            chunk = filename.split('.')
            extension = ''
            if len(chunk) > 1:
                extension = chunk[len(chunk)-1]
            extension = extension.lower()
            
            if extension not in ['mp4', 'jpg', 'gif', 'png', 'jpeg']:
                response = {
                    'status': 0,
                    'message': "Extension error!",
                }
                return HttpResponse(json.dumps(response), mimetype=mimetype)
            
            if extension == 'mp4':
                video = VideoStream.objects.create(videoupload=file, user=user)
                response = {
                    'status': 1,
                    'id': video.id,
                    'url': video.get_absolute_url(),
                    'type': 'video',
                }
            else:
                if settings.DEFAULT_FILE_STORAGE == "storages.backends.s3boto.S3BotoStorage":
                    # Now we adapt to s3 storage so need directly use rawdata                
                    photo = Photo(image=file, user=user)                
                    
                else:
                    # Origin method: only can work with local disk,
                    relative_path = "photos/%s_%s_%s" % (user_id, int(time.time()), filename)
                    full_path = os.path.join(settings.MEDIA_ROOT, relative_path)
                    # Write the file to disk
                    destination = open(full_path, 'wb+')
                    for chunk in file.chunks():
                        destination.write(chunk)
                    destination.close()
                    # Create the photo object
                    photo = Photo(image=relative_path, user=user)
                    
                    
                photo.save()
                # Photo.objects.filter(pk=photo.pk).update(user=user.id)
    
                # Try to use the spec provided
                spec = request.GET.get('spec', None)
                if not spec:
                    response = {
                        'status': 0,
                        'message': "No imagespec specified.",
                    }
                    return HttpResponse(json.dumps(response), mimetype=mimetype)
                if not hasattr(photo, spec):
                    response = {
                        'status': 0,
                        'message': "Imagespec %s does not exist." % spec,
                    }
                    return HttpResponse(json.dumps(response), mimetype=mimetype)
    
                type = request.GET.get('type', None)
                id = request.GET.get('id', None)
                if type == 'event' and id:
                    from events.models import Event
                    try:
                        event = Event.objects.get(id=id)
                        photo.attach(event)
                        photo.event = event
                        event.add_photo(photo)
                    except Event.DoesNotExist:
                        raise Http404
                response = {
                    'status': 1,
                    'id': photo.id,
                    'url': getattr(photo, spec).url,
                    'type': 'photo',
                }
        else:
            response = {
                'status': 0,
                'message': "No file could be found.",
            }
    else:
        response = {
            'status': 0,
            'message': "No file uploaded.  Please try again.",
        }
    return HttpResponse(json.dumps(response), mimetype=mimetype)
Exemple #7
0
    def getFile(self, request, vdata):
        # return {'status': 'success', 'msg': "success"}
        try:
            if isinstance(vdata, TemporaryUploadedFile):
                # Hack to fool Django, so we can keep file open in the new thread.
                vdata.file.close_called = True
            if isinstance(vdata, InMemoryUploadedFile):
                # Clone a new file for InMemeoryUploadedFile.
                # Because the old one will be closed by Django.
                vdata = SimpleUploadedFile(vdata.name, vdata.read(),
                                           vdata.content_type)
            dataFilename = vdata.name
            with open('/tmp/' + dataFilename, 'wb+') as destination:
                for chunk in vdata.chunks():
                    destination.write(chunk)
            # todo,add code to handle stuff after upload, kick off
            # destination.close()

            folder_str = time.strftime('%Y-%m-%d-%H-%M-%S',
                                       time.localtime(time.time()))
            status, output = commands.getstatusoutput(
                ("cd /tmp;mkdir -p %s;unzip %s -d %s") %
                (folder_str, dataFilename, folder_str))

            if os.path.exists('/tmp/%s/upgrade.zip' %
                              folder_str) == False or os.path.exists(
                                  '/tmp/%s/signature' % folder_str) == False:
                # messages.error(request,_('Failed to validated the upgrade package! Please check if the package is a valid Lenovo upgrade package!'))
                status, output = commands.getstatusoutput(
                    "rm -rf /tmp/%s;rm -rf /tmp/%s" %
                    (folder_str, dataFilename))
                msg = 'Failed to validated the upgrade package! Please check if the package is a valid Lenovo upgrade package!'
                return {'status': 'failed', 'msg': msg}

            if request.DATA['fileAction'] == 'unchecked':
                if os.path.exists('/tmp/%s/version.txt' % folder_str) == False:
                    status, output = commands.getstatusoutput(
                        "rm -rf /tmp/%s;rm -rf /tmp/%s" %
                        (folder_str, dataFilename))
                    msg = 'Failed to validated the upgrade package! Please check if the package contains a version.txt file!'
                    return {'status': 'failed', 'msg': msg}
                else:
                    with open('/tmp/%s/version.txt' %
                              folder_str) as versionFile:
                        data = {"UPGRADE_VERSION": "", "PATCH_ID": ""}
                        for line in versionFile.readlines():
                            props = line.split("=")
                            if props[0] in data:
                                data[props[0]] = props[1].strip("\r\n")

                    status, output = commands.getstatusoutput(
                        "rm -rf /tmp/%s;rm -rf /tmp/%s" %
                        (folder_str, dataFilename))
                    client = uus.client()
                    LOG.info("data = %s" % data)
                    up_info = client.get_upgradestatus(data["PATCH_ID"])
                    LOG.info("upinfo = %s" % up_info)
                    retstr = "PREVISION =" + up_info + "      U" + "PGRADEVERSION =" + data[
                        "UPGRADE_VERSION"]
                    if len(data["UPGRADE_VERSION"].strip()) > 0:
                        return {'status': 'success', 'msg': retstr}
                    else:
                        msg = 'Failed to validated the upgrade package! Please specific a version in the version.txt file!'
                        return {'status': 'failed', 'msg': msg}

            if os.path.exists('/etc/hwmgmt/public.pem') == False:
                # messages.error(request,_('Failed to validated the upgrade package! Please quickly contact with our department of server.'))
                status, output = commands.getstatusoutput(
                    "rm -rf /tmp/%s;rm -rf /tmp/%s" %
                    (folder_str, dataFilename))
                msg = 'Failed to validated the upgrade package! Please quickly contact with our department of server.'
                return {'status': 'failed', 'msg': msg}

            with open('/etc/hwmgmt/public.pem') as f, open('/tmp/%s/upgrade.zip' % folder_str) as message, \
                    open('/tmp/%s/signature' % folder_str) as signFile,open('/tmp/%s/version.txt' % folder_str) as versionFile:
                key = f.read()
                rsakey = RSA.importKey(key)
                verifier = Signature.new(rsakey)
                digest = SHA.new()
                digest.update(message.read())
                is_verify = verifier.verify(digest,
                                            base64.b64decode(signFile.read()))
                data = {"UPGRADE_VERSION": "", "PATCH_ID": ""}
                for line in versionFile.readlines():
                    props = line.split("=")
                    if props[0] in data:
                        data[props[0]] = props[1].strip("\r\n")

            if is_verify == False:
                # messages.error(request,_('Failed to validated the upgrade package! Please check if the package is a valid Lenovo upgrade package!'))
                status, output = commands.getstatusoutput(
                    "rm -rf /tmp/%s;rm -rf /tmp/%s" %
                    (folder_str, dataFilename))
                msg = 'Failed to validated the upgrade package! Please check if the package is a valid Lenovo upgrade package!'
                return {'status': 'failed', 'msg': msg}
            status, output = commands.getstatusoutput(
                "cd /tmp/%s;unzip upgrade.zip ;chmod +x /tmp/%s/*" %
                (folder_str, folder_str))
            execute_str = "/tmp/" + folder_str + "/upgrade.yml"
            #leverage uus to handle backend upgrade procedure, since it require root auth while we are running in as horizon user
            client = uus.client()
            return_code = 0
            try:
                with open('/tmp/%s/version.txt' % folder_str) as versionFile:
                    data = {}
                    for line in versionFile.readlines():
                        props = line.split("=")
                        data[props[0]] = props[1].strip("\r\n")
                data['workdir'] = folder_str
                return_code = client.startupgrade(execute_str, data)
                if return_code == 20301:
                    raise Exception
                msg = 'File uploaded successfully.'
                return {'status': 'success', 'msg': msg}
            except Exception as e:
                # exceptions.handle(request,_('The package can NOT work.'))
                if return_code == 20301:
                    msg = "The package has already patched!"
                else:
                    msg = 'The package can NOT work.'
                return {'status': 'failed', 'msg': msg}

            # messages.success(request,
            #                  _('Patch file %s upload success.') %
            #                  vdata.name)
        except Exception as e:
            msg = 'Unable to upload patch file'
            # TODO(nikunj2512): Fix this once it is fixed in glance client
            # exceptions.handle(request, msg)
            return {'status': 'failed', 'msg': msg}