Exemplo n.º 1
0
    def __init__(self, host, user, passwd, timeout=-999, logger=None):
        self.fp = dict()

        webdav_host = host

        self.webdav_host = webdav_host
        self.host = host
        self.user = user
        self.passwd = passwd
        self.processes = []
        self.file_queue = JoinableQueue(maxsize=0)
        self.result_queue = Queue(maxsize=0)

        self.is_alive = {
            "status": True
        }

        options = {
            'webdav_hostname': self.webdav_host,
            'webdav_login': self.user,
            'webdav_password': self.passwd
        }

        self.webdavClient = wc.Client(options)

        self.logger = logger
        self._tzinfo = TimeZoneMSK()
Exemplo n.º 2
0
 def fetchCredentials(self, WebDAVURL, credentialsFile):
     try:
         with open(credentialsFile) as credentials:
             data = credentials.readlines()
             PASSWORD = data[0].strip('\n')
             MY_ADDRESS = data[1].strip('\n')
         print("\nNC Login Credentials Obtained")
         print("--------------------------")
         print("LOGIN:    %s" % MY_ADDRESS)
         print("PASSWORD: %s\n" % (PASSWORD))
         self.changePermissions(credentialsFile)
         options = {
             'webdav_hostname': WebDAVURL,
             'webdav_login': MY_ADDRESS,
             'webdav_password': PASSWORD
         }
         client = wc.Client(options)
         return client
     except Exception as err:
         if str(err).find('connection') != -1:
             print("Connection Error:\n\t%s" % err)
             exit()
         if str(err).find('global name') != -1:
             print("Missing Library: %s" % err)
             exit()
         print("Invalid Credentials: %s" % err)
         client = self.retryLogin(credentialsFile, WebDAVURL)
         return client
Exemplo n.º 3
0
    def setUp(self):

        options = {
            'webdav_hostname': self.url,
            'webdav_login':    self.username,
            'webdav_password': self.password
            }
        self.client = wc.Client(options)
Exemplo n.º 4
0
 def report_calls(self, **req):
     print "REQ: ", req
     calls = req.get('calls')
     phonecall_obj = http.request.env['crm.phonecall'].sudo()
     user_obj = http.request.env['res.users'].sudo()
     options = {
         'webdav_hostname':
         user_obj.env.user.company_id.netelip_webdav_hostname,
         'webdav_login': user_obj.env.user.company_id.netelip_webdav_login,
         'webdav_password':
         user_obj.env.user.company_id.netelip_webdav_password,
         'webdav_root': "/remote.php/webdav"
     }
     client = wc.Client(options)
     for call_data in json.loads(calls):
         call_id = call_data['ID']
         description = call_data["dstname"]
         call = phonecall_obj.search([('name', '=', call_id)], limit=1)
         if call:
             info = description
             if 'Ext' in info:
                 if 'APIVoice' in call.description:
                     print "Desc: ", call.description
                     if client.check(call.description):
                         fname = u'/tmp/' + call.description.split('/')[-1]
                         client.download(call.description, fname)
                         f = open(fname, 'r')
                         encoded_string = base64.b64encode(f.read())
                         os.remove(fname)
                         fname = fname.split('/')[-1]
                         http.request.env['ir.attachment'].sudo().\
                             create({'name': fname,
                                     'res_name': call.name,
                              'res_model': 'crm.phonecall',
                                     'res_id': call.id,
                                     'datas': encoded_string,
                                     'datas_fname': fname})
                         client.clean(call.description)
                 extension = info.split(' ')[-1]
                 user = user_obj.search([('netelip_ext', '=', extension)],
                                        limit=1)
                 if user:
                     call.write({
                         'user_id':
                         user.id,
                         'state':
                         'done',
                         'description':
                         call.description + u'\n' + description
                     })
             else:
                 call.write({
                     'state':
                     'cancel',
                     'description':
                     call.description + u'\n' + description
                 })
Exemplo n.º 5
0
    def _init(self, **kwargs):
        """ connect to webdav server
        """

        options = {
            "webdav_hostname": f"{self.url}",
            "webdav_login": f"{self.username}",
            "webdav_password": f"{self.password}",
        }
        self.client = wc.Client(options)
    def setUp(self):
        print("username " + username)
        print("pass " + password)

        options = {
            'webdav_hostname': url,
            'webdav_login':    username,
            'webdav_password': password
            }
        client = wc.Client(options)
Exemplo n.º 7
0
 def __init__(self, hostname, username, password, max_workers=4):
     login_options = {
         'webdav_hostname': hostname,
         'webdav_login': username,
         'webdav_password': password,
         'webdav_root': '/remote.php/webdav/'
     }
     self.backup_location = "/09_SHARED_FOLDER_EXTERN/Messdaten_Feldmessung"
     self.client = wc.Client(login_options)
     logging.info("Logged Into NTB Webdav")
Exemplo n.º 8
0
def api_conectdrive():
    if request.headers['Content-Type'] == 'application/json':
        existe = 0
        datos = json.loads(request.data)
        session = requests.Session()
        session.auth = (datos['token_correo'], datos['token_contrasena'])
        verb = 'PROPFIND'
        body = '<?xml version="1.0" encoding="utf-8" ?>'
        body += '<D:propfind xmlns:D="DAV:">'
        body += '<D:allprop/></D:propfind>'
        headers = {'Depth': '1'}
        requestpath = datos['instancia'] + 'remote.php/webdav'
        response = session.request(verb,
                                   requestpath,
                                   data=body,
                                   headers=headers)
        print(response.text)
        free = response.text.split("<d:quota-available-bytes>")[1].split(
            "</d:quota-available-bytes>")[0]
        optionswebdav = {
            'webdav_hostname': requestpath,
            'webdav_login': datos["token_correo"],
            'webdav_password': datos["token_contrasena"]
        }
        clientwebdav = wc.Client(optionswebdav)
        listacarpetas = clientwebdav.list()
        print(listacarpetas)
        verb = 'MKCOL'
        headers = {}
        body = ''
        requestpath = datos['instancia'] + 'remote.php/webdav/Carpeta'
        response = session.request(verb,
                                   requestpath,
                                   data=body,
                                   headers=headers)
        mb = float(free) / 1000000
        horastotal = mb / 200
        horaspcamara = int(horastotal / len(datos['camaras']))
        for i in datos['camaras']:
            existe = False
            cursor.execute('select * from tabla where id_camara=%s' % (i[0]))
            existe = cursor.fetchone()
            print(existe)
            if existe:
                cursor.execute(
                    'update tabla set token=\'%s\', pswtoken=\'%s\', hrs_total=%s, instancia=\'%s\' where id_camara=%s;'
                    % (datos["token_correo"], datos["token_contrasena"],
                       horaspcamara, datos["instancia"], i[0]))
            else:
                cursor.execute(
                    'insert into tabla(id_camara,token,pswtoken,hrs_total,hrs_ocupadas,bandera_web,bandera_servervideo,instancia,nserie,cloud) values(%s,\'%s\',\'%s\',%s,%s,%s,%s,\'%s\',\'%s\',\'claro\');'
                    % (i[0], datos["token_correo"], datos["token_contrasena"],
                       horaspcamara, 0, True, True, datos["instancia"], i[1]))
        return "Exitoso"
Exemplo n.º 9
0
    def __init__(self):
        options = {
            'webdav_hostname': "https://carnet.live/remote.php/webdav/",
            'webdav_login': "******",
            'webdav_password': "******"
        }
        self.client = wc.Client(options)

        paths = self.list('/')

        for remote_resource_name in paths:
            print(remote_resource_name.get_etag())
Exemplo n.º 10
0
def upload_asp(TARGET):

	# create a webdav object
	print "[*] Connecting to %s" % TARGET
	webdav = easywebdav.connect(TARGET)
	# upload the file
	print "[*] Uploading payload to %s" % TARGET
	try:
		webdav.upload("not_a_shell.asp", "not_a_shell.asp;.txt")
		# use different client to move file
		options = {'webdav_hostname': TARGET}
		client = wc.Client(options)
		client.move(remote_path_from="not_a_shell.asp;.txt", remote_path_to="not_a_shell.asp")
	except:
		# if move fails try copy
		print "[*] Encountered an error"
		print "[*] Adjusting payload"
		webdav = easywebdav.connect(TARGET)
		webdav.upload("not_a_shell.asp", "not_a_shell.txt")
		options = {'webdav_hostname': TARGET}
		client = wc.Client(options)
		client.copy(remote_path_from="not_a_shell.txt", remote_path_to="not_a_shell.asp;.txt")
Exemplo n.º 11
0
    def __init__(self, hostname: str, login: str, password: str,
                 remote_path: str):
        """
        Build an instance with credentials.

        :param hostname : WebDAV link
        :param login : username
        :param password : password of the user
        :param remote_path : remote path where to store the files
        """
        options = {
            'webdav_hostname': hostname,
            'webdav_login': login,
            'webdav_password': password,
        }
        self.__remote_path = remote_path
        self.__client = wc.Client(options)
Exemplo n.º 12
0
def yadisk_upload(podcast, remote_path):
    client = wc.Client(options)
    try:
        client.upload_sync(local_path=podcast, remote_path=remote_path)
    except wc.RemoteParentNotFound as e:
        if 'parent' in str(e):
            # We create  structure!
            path_dirs = remote_path.split('/')[:-1]
            levels = []
            for directory in path_dirs:
                levels.append(directory)
                try:
                    client.mkdir('/'.join(levels))
                except:
                    pass
            # Try upload again
            client.upload_sync(local_path=podcast, remote_path=remote_path)
Exemplo n.º 13
0
def del_archieve():
    # 只考虑share_path为/flexsafe/data/volume的情况
    logger.info('正在删除存档文件')
    share_path = '/flexsafe/data/volume/'
    share_names = excuseSQL(host, ssh_account, 'flexsafe', '''SELECT share_name FROM flexsafe.archive_dir;''')
    ssh = SSHConnection(host, 22, ssh_account[0], ssh_account[1])
    options = {
        'webdav_hostname': "http://%s/remote.php/webdav" % host,
        'webdav_login': "******",
        'webdav_password': "******"
    }
    client = wc.Client(options)
    for share_name in share_names:
        print(client.clean('%s/' % share_name))
        ssh.exec_command('sudo chattr -R -i %s%s/*' % (share_path, share_name), ssh_account[1])
        ssh.exec_command('sudo rm -fr %s%s' % (share_path, share_name), ssh_account[1])

    logger.info('正在清空Flexsafe存档相关表【archive_dir】')
    excuseSQL(host, ssh_account, 'flexsafe', '''TRUNCATE TABLE archive_dir;''')
Exemplo n.º 14
0
def wef1():
    options = {
        'webdav_hostname': "https://pubdav.ctfile.com",
        'webdav_login': "******",
        'webdav_password': "******"
    }
    client = wc.Client(options)
    #检查资源的存在
    检查资源a = client.check("dir1/file1")
    检查资源b = client.check("dir1")

    #获取资源列表
    资源列表 = client.list()

    #创建一个目录
    #client.mkdir("d")

    #print('进入列表',client.cd('/'))
    print(检查资源a)
    print('资源列表', 资源列表)
Exemplo n.º 15
0
def main():

    hostname, username, password = sys.argv[1:]

    options = {
        'webdav_hostname': hostname,
        'webdav_login': username,
        'webdav_password': password,
    }

    client = wc.Client(options)

    # ignore ssl certification
    client.default_options['SSL_VERIFYPEER'] = 0
    client.default_options['SSL_VERIFYHOST'] = 0

    lst = client.list()
    print('-- LIST (count: {}) --'.format(len(lst)))
    for item in lst:
        print(' * {}'.format(item))
def f_test_webdav_conn(username, password, url):

    print("username " + username)
    print("pass " + password)

    options = {
        'webdav_hostname': url,
        'webdav_login':    username,
        'webdav_password': password
        }
    client = wc.Client(options)

    # Create Dir :
    status = client.mkdir("uploads/intergrationTesting/")
    print(status)

    # get hash file
    sha1_file_ori = f_sha1_file('/x3-apps/tux_avatars1.jpg')

    # put file
    client.upload_sync(remote_path="uploads/intergrationTesting/tux.png",
                       local_path="/x3-apps/tux_avatars1.jpg")

    # list files
    lst_files = client.list("uploads/intergrationTesting")
    print(lst_files)

    info = client.check("uploads/intergrationTesting/tux.png")
    print(info)

    # get file
    client.download_sync(remote_path="uploads/intergrationTesting/tux.png",
                         local_path="/tmp/tux.png")

    sha1_file_download = f_sha1_file('/tmp/tux.png')

    if sha1_file_ori != sha1_file_download:
        print('ERROR: Sha1 original file and downloaded file not the same')
    else:
        print('File match')
Exemplo n.º 17
0
    def yandexDisk(self, choice):

        yandexUrl = 'https://webdav.yandex.com.tr'
        options = {
         'webdav_hostname': yandexUrl,
         'webdav_login'   : prefs['username'],
         'webdav_password': prefs['password']
        }
        client = wc.Client(options)

        if (client.check() == False):
            QMessageBox.information(self, "Info", _("Login information is incorrect!"))
            return 1

        if(choice == "download"):
            if (client.check('Calibre') == False):
                client.mkdir('Calibre')
                QMessageBox.information(self, "Info", _("It was created because there is no Calibre file in Drive, download could not be done."))
            else:
                client.download_sync(remote_path="Calibre", local_path=prefs['librarypath'])
                QMessageBox.information(self, "Info", _("Download complete."))
        elif(choice == "upload"):
            if (client.check('Calibre') == False):
                client.mkdir('Calibre')
            client.upload_sync(remote_path="Calibre", local_path=prefs['librarypath'])
            QMessageBox.information(self, "Info", _("Upload complete."))
        elif(choice == "pull"):
            if (client.check('Calibre') == False):
                client.mkdir('Calibre')
                QMessageBox.information(self, "Info", _("It was created because there is no Calibre file in Drive, pull could not be done."))
            else:
                client.pull(remote_directory="Calibre", local_directory=prefs['librarypath'])
                QMessageBox.information(self, "Info", _("Pull complete."))
        elif(choice == "push"):
            if (client.check('Calibre') == False):
                client.mkdir('Calibre')
            client.push(remote_directory="Calibre", local_directory=prefs['librarypath'])
            QMessageBox.information(self, "Info", _("Push complete."))
        else:
            return 1
def check_webdav(username, password, url):
    purl = urlparse(url)

    client = wc.Client({
        'webdav_hostname': purl.scheme + "://" + purl.hostname,
        'webdav_login': username,
        'webdav_password': password
    })

    success = client.check(purl.path)
    # Workaround:
    if not success:
        res = requests.get(url, auth=(username, password))
        if res.status_code == 200:
            success = True

    if success:
        print("credentials accepted for user", username, file=sys.stderr)
        return username
    else:
        print("credentials refused for user", username, file=sys.stderr)
        return None
Exemplo n.º 19
0
    def _connect(self):

        self.is_remote_available.clear()
        self._prefix = self.kwargs["user"] + "@" + self.kwargs["host"] + ": "

        self.logger = self.kwargs.get("logger")
        if self.logger == None:
            from logger import get_logger
            self.logger = get_logger("device_mavftp", "device_webdav.log", "DEBUG")

        self.logger.info(self._prefix + "WEBDAV is unavailble. All operations is lock")

        options = {
        'webdav_hostname': self.kwargs["host"],
        'webdav_login':    self.kwargs["user"],
        'webdav_password': self.kwargs["passwd"]
        }

        # options = {
        # 'proxy_hostname':  "http://127.0.0.1:8080",
        # 'proxy_login':     "******",
        # 'proxy_password':  "******",
        # 'cert_path':       "/etc/ssl/certs/certificate.crt",
        # 'key_path':        "/etc/ssl/private/certificate.key",
        # 'recv_speed' : 3000000,
        # 'send_speed' : 3000000,
        # 'verbose'    : True
        # }

        try:
            self._wc = wc.Client(options)
        except:
            self.logger.error(self._prefix + "Import error.\nExecute: pip install webdavclient")

        if not self.is_remote_available.is_set():
            self.is_remote_available.set()
            self.logger.info(self._prefix + "WEBDAV is availble. All operations is unlock")
Exemplo n.º 20
0
    def retryLogin(self, credentialsFile, WebDAVURL):

        connected = False
        failedCount = 1
        while not connected:
            try:
                print("We can create the credentials file in Plain Text:")
                print("Press Ctrl + C to Exit/Cancel")
                MY_ADDRESS = raw_input("Enter your NextCloud Login    : "******"Enter your NextCloud Password : "******"Saved Credentials to: %s" % credentialsFile)
                connected = True
                return client

            except Exception as err:
                connected = False
                if failedCount > 3:
                    print("Exceeded '3' Failed Login Attempts:\n%s" % err)
                    exit()
                elif str(err).find('global name') != -1:
                    print("Missing Library: %s" % err)
                    exit()
                else:
                    print("Invalid Credentials: %s" % err)
                    print("Try again, or Ctrl + C to Exit:")
                    failedCount += 1
Exemplo n.º 21
0
'''

import webdav.client as wc
import glob
import time
import datetime
import os

# login configurations
# outdated
options = {
    'webdav_hostname': "https://dav.box.com/dav",
    'webdav_login': "******",
    'webdav_password': "******"
}
client = wc.Client(options)

# always check for files to upload
while True:
    # local path check
    file_list = glob.glob(os.getcwd() + '/test/*.txt')
    local_list = [os.path.basename(x) for x in file_list]

    if not (len(file_list)):
        continue
    '''
    # create a time stamp
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H%M%S')
    '''
Exemplo n.º 22
0
import webdav.client as wc

# Create WebDAV server/login details object
details = {
 'webdav_hostname': "https://dav.box.com/dav/",
 'webdav_login':    "******",
 'webdav_password': "******"
}
client = wc.Client(details)

# Create a resource
client.mkdir("folder1/folder2")

# Check for existence of a resource
client.check("folder1/file1")
client.check("folder1")

# Delete a resource (careful)
client.clean("folder1/folder2")

# Copy a resource to another location within Box
client.copy(remote_path_from="folder1/file1", remote_path_to="folder2/file1")
client.copy(remote_path_from="folder1", remote_path_to="folder2")

# Move a resource to another location within Box
client.move(remote_path_from="folder1/file1", remote_path_to="folder2/file1")
client.move(remote_path_from="folder1", remote_path_to="folder2")

# Download a resource to your local environment
client.download_sync(remote_path="folder1/file1", local_path="~/Downloads/file1")
client.download_sync(remote_path="folder1/folder2/", local_path="~/Downloads/folder/")
Exemplo n.º 23
0
 def connect(self, connect_file_path):
     with open(connect_file_path, "r") as inp:
         options = json.load(inp)
     if self.verbose:
         options['verbose'] = True
     return wc.Client(options)
Exemplo n.º 24
0
 def initial_client(self):
     self.client = wc.Client(self.options)
Exemplo n.º 25
0
    def _upload_warc(self, filename):
        import webdav.client as wc

        client = wc.Client(settings['webdav'])

        client.upload_file(filename, 'warcs/{}'.format(filename))
Exemplo n.º 26
0
    def setUp(self):

        options = {
            'webdav_hostname': self.url,
            }
        self.client = wc.Client(options)
Exemplo n.º 27
0
def webdav_client():
    return wc.Client({'webdav_hostname': 'http://localhost:29593'})
Exemplo n.º 28
0
    def load_workbook(self,
                      fname,
                      wv_user=None,
                      wv_password=None,
                      wv_host_name=None):
        """

        :param fname:
        :param wv_user: In case of use of WebDav server, user name
        :param wv_password: In case of use of WebDav server, password
        :param wv_host_name: In case of use of WebDav server, host name
        :return: Number of added DataFrames
        """
        # Load a XLSX workbook into memory, as dataframes
        pr = urlparse(fname)
        if pr.scheme != "":
            fragment = ""
            if "#" in fname:
                pos = fname.find("#")
                fragment = fname[pos + 1:]
                fname = fname[:pos]

            # Load from remote site
            if not wv_host_name:
                wv_host_name = ""
            if pr.netloc.lower() == wv_host_name:
                # WebDAV
                parts = fname.split("/")
                for i, p in enumerate(parts):
                    if p == wv_host_name:
                        url = "/".join(parts[:i + 1]) + "/"
                        fname = "/" + "/".join(parts[i + 1:])
                        break

                options = {
                    "webdav_hostname": url,
                    "webdav_login": wv_user,
                    "webdav_password": wv_password
                }
                client = wc.Client(options)
                with tempfile.NamedTemporaryFile(delete=True) as temp:
                    client.download_sync(remote_path=fname,
                                         local_path=temp.name)
                    f = open(temp.name, "rb")
                    data = io.BytesIO(f.read())
                    f.close()
            elif pr.netloc.lower() == "docs.google.com" or pr.netloc.lower(
            ) == "drive.google.com":
                # Google Drive. Only XLSX files supported (if Google Calc, an Export to XLSX is done)
                # Extract file id from the URL
                import re
                m = re.match(r".*[^-\w]([-\w]{33,})[^-\w]?.*", fname)
                file_id = m.groups()[0]
                url = f"https://docs.google.com/spreadsheets/d/{file_id}/export?format=xlsx&id={file_id}"
                resp = requests.get(url, allow_redirects=True
                                    )  # headers={'Cache-Control': 'no-cache'},
                if resp.status_code == 200:
                    data = io.BytesIO(resp.content)
            else:
                data = urllib.request.urlopen(fname).read()
                data = io.BytesIO(data)
            xl = pd.ExcelFile(
                xlrd.open_workbook(file_contents=data.getvalue()),
                engine="xlrd")
        else:
            xl = pd.ExcelFile(fname)
        cont = 0
        for sheet_name in xl.sheet_names:
            df = xl.parse(sheet_name, header=0)
            # Manage columns
            cols = []
            for col in df.columns:
                col_parts = col.split(".")
                if col.lower().startswith("unnamed"):
                    cols.append("")
                elif len(col_parts) > 1:
                    try:
                        int(col_parts[1])  # This is the case of "col.1"
                        cols.append(col_parts[0])
                    except:  # This is the case of "col_part.col_part" (second part is string)
                        cols.append(col)
                else:
                    cols.append(col)

            df.columns = cols
            self._dataframes.append(df)
            self._dataframe_names.append(sheet_name)
            cont += 1

        return cont
Exemplo n.º 29
0
credentials = {
    "user": os.environ["WEBDAV_LOGIN"],
    "pwd": os.environ["WEBDAV_PWD"],
    "host": os.environ["WEBDAV_HOST"],
    "dir": os.environ["WEBDAV_ROOTDIR"],
}

webdav_options = {
    'webdav_hostname': credentials["host"],
    'webdav_login': credentials["user"],
    'webdav_password': credentials["host"],
    'webdav_root': credentials["dir"],
    'verbose': False
}

client = wc.Client(webdav_options)


def models_available(models, path="models"):
    models_exist = True
    try:
        if not os.path.isdir(path):
            os.mkdir(path)
            models_exist = False
        for model in models:
            model_path = "{0}/{1}".format(path, model)
            if not os.path.exists(model_path):
                models_exist = False
                logging.error("please copy model {0} into folder {1}".format(
                    model, path))
    except Exception as e:
Exemplo n.º 30
0
def uploader_save():
    session = request.environ['beaker.session']
    errors = []
    messages = []
    # pp = pprint.PrettyPrinter(indent=4)
    # pp.pprint(request.forms.__dict__)
    data = {
        'hostname': request.forms['hostname'],
        'login': request.forms['login'],
        'password': request.forms['password'],
        'root': request.forms['root'],
        'url': request.forms['url'].strip(),
        'title': request.forms['title'].strip(),
        'note': request.forms['note'].strip(),
        'tags': request.forms['tags'].strip(),
    }
    upload = request.files.upload
    webdav_options = {
        'webdav_hostname': data['hostname'],
        'webdav_login': data['login'],
        'webdav_password': data['password'],
        'webdav_root': data['root'],
    }
    client = wc.Client(webdav_options)
    try:
        if data['url'] or data['note']:
            link_id = ""
            if (data['url']):
                link_id = generate_uuid_id()
                link_json = build_link_json(link_id, data['url'],
                                            data['title'], data['tags'])
                upload_link(client, link_id, link_json)
                messages.append("Uploaded Link: {0}".format(link_id))
            if (data['note']):
                note_id = generate_uuid_id()
                note_json = build_note_json(note_id, link_id, data['note'],
                                            data['tags'])
                upload_note(client, note_id, note_json)
                messages.append("Uploaded Note: {0}".format(note_id))
        elif upload:
            name, ext = os.path.splitext(upload.filename)
            if (ext == '.txt'):
                uploaded = upload_file(client, upload)
                messages.append("Uploaded: {0}".format(uploaded))
            else:
                errors.append(
                    "The file must be a text file with .txt extension")
        else:
            errors.append("URL, Note or File must be specified")
    except RemoteParentNotFound:
        errors.append("RemoteParentNotFound exception: "
                      "probably credentials are invalid")

    if len(errors) <= 0:
        data['url'] = ''
        data['title'] = ''
        data['note'] = ''
        data['tags'] = ''

    session['errors'] = errors
    session['messages'] = messages
    session['data'] = data
    redirect('/')