Beispiel #1
0
 def delete(self, p):
     if not files.exists(p):
         abort(404, message=('File not found: %s' % p))
     try:
         files.delete(p)
     except OSError as e:
         abort(501, 'File system error: ' + e.strerror)
Beispiel #2
0
 async def delete(self):
     """
     удаляет файл {filename}
     """
     file_name = self.request.match_info['file_name']
     files.delete(file_name)
     return web.json_response({'deleted_file': file_name})
Beispiel #3
0
def main():
    if len(sys.argv) <= 1:
        print "Please Set Argv Resource Path"
        return

    resourcePath = sys.argv[1]
    absResourcePath = os.path.abspath(resourcePath)
    sid = session.getSessionId()
    downloadFilePath = files.getDownloadPath(sid)
    zipFile = files.download(sid, downloadFilePath)
    files.unarchive(zipFile, absResourcePath)
    files.delete(zipFile)
Beispiel #4
0
def file_action():
    error = None
    action = request.form['button']
    p = request.form['p']
    fs = [k[5:] for k in request.form.iterkeys() if k.startswith('file_')]
    if action == 'Delete':
        for f in fs:
            try:
                files.delete('/%s/%s' % (p, f))
            except OSError as e:
                error = 'Error deleting %s: %s' % (f, e.strerror)
                break
            except IOError as e:
                error = 'Error deleting %s: %s' % (f, e.strerror)
                break
        return file_listing(p, error)
    elif action in ['Cut', 'Copy']:
        session['clipboard'] = action
        users.set_clipboard(g.user_id, ['/%s/%s' % (p, f) for f in fs])
        return file_listing(p, None)
Beispiel #5
0
def file_action():
    error = None
    action = request.form['button']
    p = request.form['p']
    fs = [k[5:]
          for k in request.form.iterkeys()
          if k.startswith('file_')]
    if action == 'Delete':
        for f in fs:
            try:
                files.delete('/%s/%s' % (p, f))
            except OSError as e:
                error = 'Error deleting %s: %s' % (f, e.strerror)
                break
            except IOError as e:
                error = 'Error deleting %s: %s' % (f, e.strerror)
                break
        return file_listing(p, error)
    elif action in ['Cut', 'Copy']:
        session['clipboard'] = action
        users.set_clipboard(g.user_id, ['/%s/%s' % (p, f) for f in fs])
        return file_listing(p, None)
Beispiel #6
0
            if args.dest_id:
                files.upload(args.upload, args.dest_id)
            else:
                print("--upload necesita --dest_id")

        elif args.list_files:
            files.list_files()

        elif args.download:
            if args.source_id:
                files.download(args.download, args.source_id)
            else:
                print("--download necesita --source_id")

        elif args.delete_file:
            files.delete(args.delete_file)

        # Para encriptar pedimos la clave publica del destinatario, ciframos
        # y guardamos el fichero encriptado en path_archivos
        elif args.encrypt:
            if args.dest_id:
                publicKey = users.get_public_key(args.dest_id)
                if publicKey is not None:
                    try:
                        f = open(args.encrypt, "rb")
                        mensaje_cifrado = crypto.encrypt(f.read(), publicKey)
                        f.close()
                        # Si se ha cifrado correctamente lo guardamos como: enc_ + nombre del fichero
                        if mensaje_cifrado is not None:
                            file_name = os.path.basename(args.encrypt)
                            f = open(u.path_archivos + "enc_" + file_name,
Beispiel #7
0
def delete():
    files.delete(legoName.get())
    raise_frame(f1)
Beispiel #8
0
            # this prevents overwriting the leader_message_id key as the updating is handled async and is faster
            # yes i know this is not good, I will look to improve this
            try:
                data_with_id = files.read(f'data/{message.guild.id}.pkl')
                data["leaderboard_message_id"] = data_with_id[
                    "leaderboard_message_id"]
            except KeyError:
                pass
            if (data["count"] - 1) % 100 == 0:
                print(
                    f"{current_time} on {message.guild}: Server reached {message.content}"
                )
            files.write(f"data/{message.guild.id}.pkl", data)
        else:
            await message.delete()

    if str(message.channel) == "leaderboard":
        # As all bot actions quit the function before so this is safe
        await message.delete()
    return


# Run the bot
try:
    bot.run(token)
except discord.errors.LoginFailure:
    print("STARTUP_ERROR: TOKEN INVALID \n deleting token.pkl")
    files.delete("data/token.pkl")
    exit(1)
Beispiel #9
0
    def files_list_view(self):
        if not 'password' in self.request.POST and self.check():
            print self.request.POST
            return HTTPFound(location='/login')
        url = USB_LOCATION + get_url(self.request.matchdict['list'])
        url_parsed = '/'
        for i in range(len(url.split('/')) - 3):
            url_parsed += url.split('/')[i + 1] + '/'
        action = url.split('/')[-2]
        filename = str(url_parsed.split('/')[-2])
        if 'password' in self.request.POST:
            if self.request.POST['password'] != '':
                password = self.request.POST['password']
#                print password
                content = encrypt(self.request.POST['notecontent'], password)
                write('/'.join(url.split('/')[:-2]), content)
                return HTTPFound(location='/files' + url[:-1])
#                return Response()
        elif 'file' in self.request.POST:
            filename = self.request.POST['file'].filename
            print filename
            input_file = self.request.POST['file'].file
            upload(input_file, url, filename)
            print '/files' + url
            return HTTPFound(location='/files' + url)
        elif 'dir_name' in self.request.POST:
            dirname = self.request.POST['dir_name']
            make_dir(dirname, url)
            return HTTPFound(location='/files' + url)
        elif 'note_name' in self.request.POST:
            write(url + self.request.POST['note_name'], '')
            return HTTPFound(location='/files' + url)
        elif 'notecontent' in self.request.POST:
            content = encrypt(self.request.POST['notecontent'], decrypt(self.request.session['enpass'], self.request.cookies['r']))
            write('/'.join(url.split('/')[:-2]), content)
            return HTTPFound(location='/files' + url)
        elif action == 'edit':
            content = decrypt(read(url_parsed[:-1]), decrypt(self.request.session['enpass'], self.request.cookies['r']))
            re = { 'page_title' : 'Notes', 'edit' : True, 'contents' : content, 'url' : url }
            re.update(self.get_header())
            return re
        elif action == 'rename':
            # file_old = str(url_parsed.split('/')[-3])
            file_old = '/'.join(url_parsed.split('/')[:-2])
            if not is_file('/'.join(url_parsed.split('/')[:-2])) and not is_dir('/'.join(url_parsed.split('/')[:-2])):
                print 'not filename'
                return HTTPFound(location='/files')
            rename(file_old, filename)
            return HTTPFound('/files' + '/'.join(url.split('/')[:-4]))
        elif is_file(url_parsed[:-1]):
            if action == 'download':
                re = FileResponse(url_parsed[:-1])

                re.headers['Content-Disposition'] = 'attachment; filename="' + filename + '"'
                re.headers['Content-Type'] = 'application/force-download'
#                re.headers['filename'] = filename
                re.headers['Accept-Ranges'] = 'bytes'
                return re
            elif action == 'delete':
                delete(url_parsed[:-1])
                return HTTPFound(self.request.url[:-7-len(filename.replace(' ', '%20'))])
        elif is_dir(url[:-7]) and action == 'delete':
            delete(url[:-7])
            return HTTPFound(self.request.url[:-7-len(filename)])
        elif not is_dir(url) or len(url.split('/')) < 5:
            return HTTPFound(location='/files')
        temp = [str(part) for part in list_dir(url)]
        temp.sort(lambda x, y: cmp(x.lower(),y.lower()))
        item_list = [ { 'url' : '/files/' + url[1:] + part if is_dir(url + part) else '/files/' + url[1:] + part + '/download', 'url_ren' : '/files/' + url[1:] + part, 'url_del' : '/files/' + url[1:] + part + '/delete', 'name' : part, 'is_file' : is_file(url + part), 'size' : size(url + part) } for part in temp ]
        
        re = {'page_title': LINKS['files_list']['title'], 'list' : item_list, 'up_dir' : '/files/' + url_parsed[1:], 'url' : url, 'edit' : False }
        re.update(self.get_header())
        return re
def files_tests():
    from files import (readall, writeall, exists, copy, move, sep, run, isemptydir, listchildren, makedir,
        getname, listfiles, recursedirs, recursefiles, delete, runWithoutWaitUnicode)
    import tempfile
    import os
    import shutil
    tmpdir = tempfile.gettempdir() + sep + 'pytest'
    tmpdirsl = tmpdir + sep
    if not os.path.exists(tmpdir):
        os.mkdir(tmpdir)

    def cleardirectoryfiles(d):
        shutil.rmtree(d)
        os.mkdir(d)
        assertTrue(isemptydir(d))
    
    # test copy_overwrite, source not exist
    cleardirectoryfiles(tmpdir)
    assertException(lambda: copy(tmpdirsl + 'src.txt', tmpdirsl + 'srccopy.txt', True), IOError)
    
    # test copy_overwrite, simple copy
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    copy(tmpdirsl + 'src.txt', tmpdirsl + 'srccopy.txt', True)
    assertEq('src', readall(tmpdirsl + 'srccopy.txt'))
    assertTrue(exists(tmpdirsl + 'src.txt'))
    
    # test copy_overwrite, overwrite
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    assertEq('src', readall(tmpdirsl + 'src.txt'))
    writeall(tmpdirsl + 'dest.txt', 'dest')
    assertEq('dest', readall(tmpdirsl + 'dest.txt'))
    copy(tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt', True)
    assertEq('src', readall(tmpdirsl + 'dest.txt'))
    assertTrue(exists(tmpdirsl + 'src.txt'))
    
    # test copy_nooverwrite, source not exist
    cleardirectoryfiles(tmpdir)
    assertException(lambda: copy(tmpdirsl + 'src.txt', tmpdirsl + 'srccopy.txt', False), IOError)
    
    # test copy_nooverwrite, simple copy
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    copy(tmpdirsl + 'src.txt', tmpdirsl + 'srccopy.txt', False)
    assertEq('src', readall(tmpdirsl + 'srccopy.txt'))
    
    # test copy_nooverwrite, simple overwrite should fail
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    assertEq('src', readall(tmpdirsl + 'src.txt'))
    writeall(tmpdirsl + 'dest.txt', 'dest')
    assertEq('dest', readall(tmpdirsl + 'dest.txt'))
    if sys.platform == 'win32':
        assertException(lambda: copy(tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt', False), IOError, 'CopyFileW failed')
    else:
        assertException(lambda: copy(tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt', False), OSError, 'File exists')
    assertEq('dest', readall(tmpdirsl + 'dest.txt'))
    
    # test move_overwrite, source not exist
    cleardirectoryfiles(tmpdir)
    assertException(lambda: move(tmpdirsl + 'src.txt', tmpdirsl + 'srcmove.txt', True), IOError)
    assertTrue(not exists(tmpdirsl + 'src.txt'))
    
    # test move_overwrite, simple move
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    move(tmpdirsl + 'src.txt', tmpdirsl + 'srcmove.txt', True)
    assertEq('src', readall(tmpdirsl + 'srcmove.txt'))
    assertTrue(not exists(tmpdirsl + 'src.txt'))
    
    # test move_overwrite, overwrite
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    assertEq('src', readall(tmpdirsl + 'src.txt'))
    writeall(tmpdirsl + 'dest.txt', 'dest')
    assertEq('dest', readall(tmpdirsl + 'dest.txt'))
    move(tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt', True)
    assertEq('src', readall(tmpdirsl + 'dest.txt'))
    assertTrue(not exists(tmpdirsl + 'src.txt'))
    
    # test move_nooverwrite, source not exist
    cleardirectoryfiles(tmpdir)
    assertException(lambda: move(tmpdirsl + 'src.txt', tmpdirsl + 'srcmove.txt', False), IOError)
    assertTrue(not exists(tmpdirsl + 'src.txt'))
    
    # test move_nooverwrite, simple move
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    move(tmpdirsl + 'src.txt', tmpdirsl + 'srcmove.txt', False)
    assertEq('src', readall(tmpdirsl + 'srcmove.txt'))
    assertTrue(not exists(tmpdirsl + 'src.txt'))
    
    # test move_nooverwrite, simple overwrite should fail
    cleardirectoryfiles(tmpdir)
    writeall(tmpdirsl + 'src.txt', 'src')
    assertEq('src', readall(tmpdirsl + 'src.txt'))
    writeall(tmpdirsl + 'dest.txt', 'dest')
    assertEq('dest', readall(tmpdirsl + 'dest.txt'))
    if sys.platform == 'win32':
        assertException(lambda: move(tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt', False), IOError, 'MoveFileExW failed')
    else:
        assertException(lambda: move(tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt', False), OSError, 'File exists')
    assertEq('dest', readall(tmpdirsl + 'dest.txt'))
    assertTrue(exists(tmpdirsl + 'src.txt'))
    
    # test _checkNamedParameters
    assertException(lambda: list(listchildren(tmpdir, True)), ValueError, 'please name parameters')
    
    # tmpdir has files, dirs
    # tmpdir/s1 has no files, dirs
    # tmpdir/s1/ss1 has files, no dirs
    # tmpdir/s1/ss2 has no files, dirs
    cleardirectoryfiles(tmpdir)
    dirstomake = [tmpdir, tmpdirsl + 's1', tmpdirsl + 's1' + sep + 'ss1', tmpdirsl + 's1' + sep + 'ss2', tmpdirsl + 's2']
    filestomake = [tmpdirsl + 'P1.PNG', tmpdirsl + 'a1.txt', tmpdirsl + 'a2png',
        tmpdirsl + 's1' + sep + 'ss1' + sep + 'file.txt', tmpdirsl + 's2' + sep + 'other.txt']
    for dir in dirstomake:
        if dir != tmpdir:
            makedir(dir)
    for file in filestomake:
        writeall(file, 'content')
    
    # test listchildren
    expected = ['P1.PNG', 'a1.txt', 'a2png', 's1', 's2']
    assertEq([(tmpdirsl + s, s) for s in expected], sorted(list(listchildren(tmpdir))))
    assertEq(expected, sorted(list(listchildren(tmpdir, filenamesOnly=True))))
    assertEq(['P1.PNG', 'a1.txt'], sorted(list(listchildren(tmpdir, filenamesOnly=True, allowedexts=['png', 'txt']))))
    
    # test listfiles
    expected = ['P1.PNG', 'a1.txt', 'a2png']
    assertEq([(tmpdirsl + s, s) for s in expected], sorted(list(listfiles(tmpdir))))
    assertEq(expected, sorted(list(listfiles(tmpdir, filenamesOnly=True))))
    assertEq(['P1.PNG', 'a1.txt'], sorted(list(listfiles(tmpdir, filenamesOnly=True, allowedexts=['png', 'txt']))))
    
    # test recursefiles
    assertEq([(s, getname(s)) for s in filestomake],
        sorted(list(recursefiles(tmpdir))))
    assertEq([getname(s) for s in filestomake],
        sorted(list(recursefiles(tmpdir, filenamesOnly=True))))
    assertEq(['a1.txt', 'file.txt', 'other.txt'],
        sorted(list(recursefiles(tmpdir, filenamesOnly=True, allowedexts=['txt']))))
    assertEq(['a1.txt', 'file.txt', 'other.txt'],
        sorted(list(recursefiles(tmpdir, filenamesOnly=True, allowedexts=['txt'], fnFilterDirs=lambda d: True))))
    assertEq(['a1.txt'],
        sorted(list(recursefiles(tmpdir, filenamesOnly=True, allowedexts=['txt'], fnFilterDirs=lambda d: False))))
    assertEq(['a1.txt', 'other.txt'],
        sorted(list(recursefiles(tmpdir, filenamesOnly=True, allowedexts=['txt'], fnFilterDirs=lambda dir: getname(dir) != 's1'))))
    assertEq(['a1.txt', 'file.txt'],
        sorted(list(recursefiles(tmpdir, filenamesOnly=True, allowedexts=['txt'], fnFilterDirs=lambda dir: getname(dir) != 's2'))))
    
    # test recursedirs
    assertEq(sorted([(s, getname(s)) for s in dirstomake]), sorted(list(recursedirs(tmpdir))))
    assertEq(sorted([getname(s) for s in dirstomake]), sorted(list(recursedirs(tmpdir, filenamesOnly=True))))
    assertEq(['pytest', 's2'], sorted(list(recursedirs(tmpdir, filenamesOnly=True, fnFilterDirs=lambda dir: getname(dir) != 's1'))))
    
    # test run process, simple batch script
    if sys.platform == 'win32':
        cleardirectoryfiles(tmpdir)
        writeall(tmpdirsl + 'src.txt', 'src')
        writeall(tmpdirsl + 'script.bat', 'copy "%ssrc.txt" "%sdest.txt"'%(tmpdirsl, tmpdirsl))
        assertTrue(not exists(tmpdirsl + 'dest.txt'))
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat'])
        assertEq(0, returncode)
        assertTrue(exists(tmpdirsl + 'dest.txt'))
        
        # specify no capture and run again
        delete(tmpdirsl + 'dest.txt')
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat'], captureoutput=False)
        assertEq(0, returncode)
        assertTrue(exists(tmpdirsl + 'dest.txt'))
        
        # run process with unicode characters
        delete(tmpdirsl + 'dest.txt')
        unicodepath = tmpdirsl + u'scr#1pt#2.bat'.replace('#1', u'\u012B').replace('#2', u'\u013C')
        writeall(unicodepath, 'copy "%ssrc.txt" "%sdest.txt"'%(tmpdirsl, tmpdirsl))
        try:
            import time
            runWithoutWaitUnicode([unicodepath])
            time.sleep(0.5)
            assertTrue(exists(tmpdirsl + 'dest.txt'))
        finally:
            delete(unicodepath)
        
        # test run process, batch script returns failure
        cleardirectoryfiles(tmpdir)
        writeall(tmpdirsl + 'script.bat', '\nexit /b 123')
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat'], throwOnFailure=False)
        assertEq(123, returncode)
        # specify no capture and run again
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat'], throwOnFailure=False, captureoutput=False)
        assertEq(123, returncode)
        # except exception
        assertException(lambda: run([tmpdirsl + 'script.bat']), RuntimeError, 'retcode is not 0')
        # specify no capture, except exception
        assertException(lambda: run([tmpdirsl + 'script.bat'], captureoutput=False), RuntimeError, 'retcode is not 0')
        
        # test run process, get stdout
        writeall(tmpdirsl + 'script.bat', '\n@echo off\necho testecho')
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat'])
        assertEq(0, returncode)
        assertEq('testecho', stdout)
        assertEq('', stderr)
        
        # test run process, get stderr
        writeall(tmpdirsl + 'script.bat', '\n@echo off\necho testechoerr 1>&2')
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat'])
        assertEq(0, returncode)
        assertEq('', stdout)
        assertEq('testechoerr', stderr)
        
        # test run process, get both. (this deadlocks if done naively, but it looks like subprocess correctly uses 2 threads.)
        writeall(tmpdirsl + 'script.bat', '\n@echo off\necho testecho\necho testechoerr 1>&2')
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat'])
        assertEq(0, returncode)
        assertEq('testecho', stdout)
        assertEq('testechoerr', stderr)
        
        # test run process, send argument without spaces
        writeall(tmpdirsl + 'script.bat', '\n@echo off\necho %1')
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat', 'testarg'])
        assertEq(0, returncode)
        assertEq('testarg', stdout)
        
        # test run process, send argument with spaces (subprocess will quote the args)
        writeall(tmpdirsl + 'script.bat', '\n@echo off\necho %1')
        returncode, stdout, stderr = run([tmpdirsl + 'script.bat', 'test arg'])
        assertEq(0, returncode)
        assertEq('"test arg"', stdout)
        
        # test run process, run without shell
        cleardirectoryfiles(tmpdir)
        writeall(tmpdirsl + 'src.txt', 'src')
        # won't work without the shell:
        assertException(lambda: run(['copy', tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt']), OSError)
        assertTrue(not exists(tmpdirsl + 'dest.txt'))
        # will work with the shell
        returncode, stdout, stderr = run(['copy', tmpdirsl + 'src.txt', tmpdirsl + 'dest.txt'], shell=True)
        assertEq(0, returncode)
        assertTrue(exists(tmpdirsl + 'dest.txt'))