Exemplo n.º 1
0
def upload(request):
    if request.user.is_authenticated:

        # User is authenticated and is selecting a file
        if request.method == 'GET':
            return render(request, 'file/upload.html', status=200)

        # This Part takes acre of uploading of file by passing request.Files object
        if request.method == 'POST':
            # Try to upload a file
            try:
                file_name, file_path = handle_uploaded_file(
                    request, request.FILES['file'], str(request.FILES['file']))
                # Creating A file Record for user uploaded file in Database
                filevar = File(name=file_name,
                               user=request.user,
                               path=file_path)
                filevar.save()
                # ReDirect to home page after uploading
                return HttpResponseRedirect("/")
            except KeyError:
                return HttpResponseRedirect("/upload")
            except ValueError:
                return HttpResponse("File Already Exists", status=400)
        else:
            return HttpResponse("Unsupported method Please use GET or POST ",
                                status=405)
    else:
        # User is not logged but is trying to access upload url
        return HttpResponseRedirect("/login")
Exemplo n.º 2
0
def user_files(request):
    try:
        user_user = User.objects.get(username=request.session['user'])
        user_my = MyUser.objects.get(user=user_user)
        if request.method == 'POST':
            form = FileForm(request.POST, request.FILES)

            if form.is_valid():
                newfile = File(content=request.FILES['content'])
                newfile.save()
                file_hash = hash_file(newfile.content.path)
                user_my.file_number += 1
                user_my.save()
                user_file_name = newfile.content.name[6:]
                try:
                    check_user_file = UserFiles.objects.get(file_user=user_my)

                    if file_hash == check_user_file.file_hash:
                        request.session['uploaded_file_status'] = ['This file already uploaded with name: %s' % check_user_file.file_name]
                        return HttpResponseRedirect(reverse('file.views.user_files'))
                    elif user_file_name == check_user_file.file_name:
                        request.session['uploaded_file_status'] = ['You already have file with such name: %s' % user_file_name]
                        return HttpResponseRedirect(reverse('file.views.user_files'))
                except UserFiles.DoesNotExist:
                    pass

                if os.path.isfile(MEDIA_ROOT + '/' + file_hash):
                    request.session['uploaded_file_status'] = duplicate_file_message(file_hash)
                    file = File.objects.get(content=file_hash)
                    file.file_links += 1
                    file.save()
                else:
                    request.session['uploaded_file_status'] = ['File is loaded successfully']
                    os.rename(newfile.content.path, MEDIA_ROOT + '/' + file_hash)
                    newfile.content.name = file_hash
                    newfile.file_links += 1
                newfile.save()
                userfile = UserFiles(file_hash=file_hash, file_name=user_file_name, file_user=user_my)
                userfile.save()

                return HttpResponseRedirect(reverse('file.views.user_files'))
        else:
            form = FileForm()

        files = UserFiles.objects.filter(file_user=user_my)

        return render_to_response(
            'files.html',
            {
                'files': files,
                'form': form,
                'username': auth.get_user(request).username,
                'uploaded_file_status': request.session['uploaded_file_status'],
            },
            context_instance=RequestContext(request)
        )
    except KeyError:
        redirect('/auth/login/')
Exemplo n.º 3
0
def put(request, public_key, secret_key):
	account = get_object_or_404(Account, 'public_key =', public_key, 'secret_key =', secret_key)
	request_file = request.FILES['myfile']
	file = File(
		name = request_file.name,
		data = request_file.read(),
		owner = account,
		added_date = datetime.now(),
		size = request_file.size
	)
	
	file.put()
	
	return HttpResponse(file.key())
    def create(self, validated_data):
        # self.initial_data to get the keys from frontend sent data
        request = self.context.get("request")

        is_submitted = validated_data.get('is_submitted', False)
        is_snippet = request.data['is_snippet']

        creator_id = validated_data.get('creator_id', "")
        user_obj = User.objects.get(pk=creator_id)
        exercise_instance = Exercise.objects.get(pk=request.data['exercise'])
        print("is_snippet===============", is_snippet)
        if is_snippet == str(True):
            print("in IF")
            snippet = request.data['snippet']

            filename = f'{user_obj.username}_{exercise_instance.name}.txt'
            f = open(
                filename,
                "w+",
                encoding="utf-8"
            )

            f.write(snippet)
            print(type(f))
            file_obj = f
            print("file_obj=========", file_obj)

        else:
            filename = validated_data.get('name', "")
            file_obj = validated_data.get('file_obj', "")

        exercise_instance = Exercise.objects.get(pk=request.data['exercise'])
        subject_id = self.initial_data['subject_id']
        from django.core.files import File as filex
        file_obj = filex(file_obj)
        new_file = File(
            name=filename,
            is_submitted=is_submitted,
            file_obj=file_obj,
            creator_id=creator_id,
            user=user_obj,
            exercise=exercise_instance,
            subject_id=subject_id
        )

        new_file.save()
        return new_file
Exemplo n.º 5
0
 def post(self, request, *args, **kwargs):
     begin_time = time.time()
     files = request.FILES.getlist('path')
     # print(files)
     file_list = []
     # file_list = [File(name=f.name.rstrip('"'), path=f) for f in files]
     for f in files:
         file_list.append(File(name=f.name, path=f))
     File.objects.bulk_create(file_list)
     print(time.time() - begin_time)
    def create(self, validated_data):
        name = validated_data.get('name', "")
        is_submitted = validated_data.get('is_submitted', False)
        file_obj = validated_data.get('file_obj', "")
        creator_id = validated_data.get('creator_id', "")
        print('creator id============ ', creator_id)
        userObj = User.objects.get(pk=creator_id)
        print('userObj ============', userObj)
        # serializer = UserSerializer(userObj)
        request = self.context['request']
        # print(serializer)
        user = validated_data.get('user')
        file_binary = validated_data.get('file_binary', "")
        file = File(name=name,
                    is_submitted=is_submitted,
                    file_obj=file_obj,
                    creator_id=creator_id,
                    user=userObj,
                    file_binary=file_binary)

        file.save()
        return file
Exemplo n.º 7
0
def upload(request):
	user = User.get_user_session(request.session)


	if (user == None):
		return HttpResponse("you can't upload file, please login")

	if user.access_level > 1:
			return HttpResponse("you don't have authority to upload file")

	if request.method == 'POST':
		dir = File.try_save(request.POST, request.FILES['file'], user)
		return HttpResponse('Your file path is<br><a href="/%s%s">/%s%s</a><br>It can be directly pasted in a wiki link.' % (settings.FILE_DIR, dir, settings.FILE_DIR, dir) )
	context = {'site': settings.SITE, 'session': request.session}
	return render(request, 'file/upload.html', context)
Exemplo n.º 8
0
 def uploadFile(self, user, name, fileType, route, files):
     try:
         if (route == ""):
             return "Error"
         elif (name == ""
               ):  #the name will be the original one from the file
             newName = files.name
             newImage = File(name=newName,
                             fileType=fileType,
                             parent=user + '/' + route)
             newImage.save()
             f = open(
                 'resources/Projects/' + user + '/' + route + '/' + newName,
                 'w', 0664)
             for chunk in files.chunks():
                 f.write(chunk)
             f.close()
             response = []
             response.append({
                 'parent': route,
                 'id': newName,
                 'type': fileType
             })
             return json.JSONEncoder().encode(response)
         else:
             newImage = File(name=name,
                             fileType=fileType,
                             parent=user + '/' + route)
             newImage.save()
             f = open(
                 'resources/Projects/' + user + '/' + route + '/' + name,
                 'w', 0664)
             for chunk in files.chunks():
                 f.write(chunk)
             f.close()
             response = []
             response.append({
                 'parent': route,
                 'id': name,
                 'type': fileType
             })
             return json.JSONEncoder().encode(response)
     except:
         return "Error"
Exemplo n.º 9
0
    def post(self, request, format=None):
        folder = get_object_or_404(
            Folder, pk=request.POST['folder']
        )  #Folder.objects.get(pk = request.POST['folder'])

        file = File()
        file.extension = request.FILES['file'].name.split('.')[-1]
        file.name = request.FILES['file'].name.replace('.' + file.extension,
                                                       '')
        file.folder = folder
        path = self.getAvailablePath(file, folder)
        file.save()

        with open(path, 'wb+') as destination:
            for chunk in request.FILES['file'].chunks():
                destination.write(chunk)

        return HttpResponse("OK")
Exemplo n.º 10
0
    def get(self, request, pk, dest, format=None):
        """
        Copy the content of the first file in the second file.
        """

        # TODO riguardare l'implementazione
        file = get_object_or_404(File, pk=pk)  #File.objects.get(pk = pk)
        folder = Folder.objects.get(pk=file.folder_id)
        path = settings.DATA_PATH + folder.getPath(
        ) + file.name + '.' + file.extension
        dest = get_object_or_404(Folder,
                                 pk=dest)  #Folder.objects.get(pk = dest)
        newfile = File()
        newfile.name = file.name
        newfile.extension = file.extension
        newfile.folder = dest
        destPath = self.getAvailablePath(newfile, dest)
        #destPath = settings.DATA_PATH + dest.getPath() + file.name + '.' + file.extension
        #subprocess.call(f'cp "{path}" "{destPath}"', shell=True)
        copyfile(path, destPath)
        newfile.save()
        return HttpResponse("OK")
Exemplo n.º 11
0
def user_files(request):
    try:
        user_user = User.objects.get(username=request.session['user'])
        user_my = MyUser.objects.get(user=user_user)
        if request.method == 'POST':
            form = FileForm(request.POST, request.FILES)

            if form.is_valid():
                newfile = File(content=request.FILES['content'])
                newfile.save()
                file_hash = hash_file(newfile.content.path)
                user_my.file_number += 1
                user_my.save()
                user_file_name = newfile.content.name[6:]
                try:
                    check_user_file = UserFiles.objects.get(file_user=user_my)

                    if file_hash == check_user_file.file_hash:
                        request.session['uploaded_file_status'] = [
                            'This file already uploaded with name: %s' %
                            check_user_file.file_name
                        ]
                        return HttpResponseRedirect(
                            reverse('file.views.user_files'))
                    elif user_file_name == check_user_file.file_name:
                        request.session['uploaded_file_status'] = [
                            'You already have file with such name: %s' %
                            user_file_name
                        ]
                        return HttpResponseRedirect(
                            reverse('file.views.user_files'))
                except UserFiles.DoesNotExist:
                    pass

                if os.path.isfile(MEDIA_ROOT + '/' + file_hash):
                    request.session[
                        'uploaded_file_status'] = duplicate_file_message(
                            file_hash)
                    file = File.objects.get(content=file_hash)
                    file.file_links += 1
                    file.save()
                else:
                    request.session['uploaded_file_status'] = [
                        'File is loaded successfully'
                    ]
                    os.rename(newfile.content.path,
                              MEDIA_ROOT + '/' + file_hash)
                    newfile.content.name = file_hash
                    newfile.file_links += 1
                newfile.save()
                userfile = UserFiles(file_hash=file_hash,
                                     file_name=user_file_name,
                                     file_user=user_my)
                userfile.save()

                return HttpResponseRedirect(reverse('file.views.user_files'))
        else:
            form = FileForm()

        files = UserFiles.objects.filter(file_user=user_my)

        return render_to_response(
            'files.html', {
                'files': files,
                'form': form,
                'username': auth.get_user(request).username,
                'uploaded_file_status':
                request.session['uploaded_file_status'],
            },
            context_instance=RequestContext(request))
    except KeyError:
        redirect('/auth/login/')
Exemplo n.º 12
0
 def __saveFile(self, user, fileToSave):
     try:
         if fileToSave[u'parent'] != None:
             rawFile = File.objects.filter(parent=user + '/' +
                                           fileToSave[u'parent']).filter(
                                               name=fileToSave[u'id'])
             if len(rawFile) == 0:
                 if fileToSave[u'type'] == u'dir':
                     newFile = File(name=fileToSave[u'id'],
                                    fileType=fileToSave[u'type'],
                                    parent=user + '/' +
                                    fileToSave[u'parent'])
                     newFile.save()
                     os.mkdir(
                         'resources/Projects/' + user + '/' +
                         fileToSave[u'parent'] + '/' + fileToSave[u'id'],
                         0775)
                 else:
                     newFile = File(name=fileToSave[u'id'],
                                    fileType=fileToSave[u'type'],
                                    parent=user + '/' +
                                    fileToSave[u'parent'],
                                    syntax=fileToSave[u'syntax'])
                     newFile.save()
                     f = open(
                         'resources/Projects/' + user + '/' +
                         fileToSave[u'parent'] + '/' + fileToSave[u'id'],
                         'w', 0664)
                     f.close()
                 return True
             else:
                 rawFile[0].text = fileToSave[u'text']
                 rawFile[0].syntax = fileToSave[u'syntax']
                 rawFile[0].save()
                 f = open(
                     'resources/Projects/' + user + '/' +
                     fileToSave[u'parent'] + '/' + fileToSave[u'id'], 'w')
                 length = len(fileToSave[u'text'])
                 i = 0
                 while (i + 64 < length - 1):
                     f.write(fileToSave[u'text'][i:i + 64])
                     i = i + 64
                 f.write(fileToSave[u'text'][i:i + 64])
                 f.close()
                 return True
         else:
             #is a project
             rawFile = File.objects.filter(parent=user).filter(
                 name=fileToSave[u'id'])
             if len(rawFile) == 0:  #create new project
                 newFile = File(name=fileToSave[u'id'],
                                fileType=fileToSave[u'type'],
                                parent=user)
                 newFile.save()
                 if not os.path.isdir('resources/Projects/' + user):
                     os.mkdir('resources/Projects/' + user)
                 os.mkdir(
                     'resources/Projects/' + user + '/' + fileToSave[u'id'],
                     0775)
                 imagesFolder = File(name=u'images',
                                     fileType=u'dir',
                                     parent=user + '/' + fileToSave[u'id'])
                 imagesFolder.save()
                 os.mkdir(
                     'resources/Projects/' + user + '/' +
                     fileToSave[u'id'] + '/images', 0775)
                 versionFolder = File(name=u'v1.0',
                                      fileType=u'dir',
                                      parent=user + '/' + fileToSave[u'id'])
                 versionFolder.save()
                 os.mkdir(
                     'resources/Projects/' + user + '/' +
                     fileToSave[u'id'] + '/v1.0', 0775)
                 templateFile = File(name=u'template.xml',
                                     fileType=u'template',
                                     parent=user + '/' + fileToSave[u'id'] +
                                     '/v1.0',
                                     syntax=u'xml')
                 templateFile.save()
                 tFile = open(
                     'resources/Projects/' + user + '/' +
                     fileToSave[u'id'] + '/v1.0/template.xml', 'w')
                 tFile.close()
                 indexFile = File(name=u'index.html',
                                  fileType=u'code',
                                  parent=user + '/' + fileToSave[u'id'] +
                                  '/v1.0',
                                  syntax=u'html')
                 indexFile.save()
                 iFile = open(
                     'resources/Projects/' + user + '/' +
                     fileToSave[u'id'] + '/v1.0/index.html', 'w')
                 iFile.close()
                 return True
             else:  # error
                 return False
     except:
         return False