def getFileHistory(filename):
        from SugarSyncFile import SugarSyncFile
        sync = SugarSyncInstance.instance

        response = sync.sendRequest('/file/%s/version' % filename, {}, True,
                                    False)
        files = None

        if response is not False and response is not None:
            info = response.info()
            code = response.getcode()
            data = XMLElement.parse(response.read().decode('utf8'))

            # We will parse into SugarSyncFile and then return an dict maybe sorted after
            # lastModified
            if code == 200 and data is not None:
                files = []
                for fv in data.childs:
                    version = SugarSyncFile(fv.ref)
                    version.setSize(fv.size)
                    version.setMediaType(str(fv.mediaType))
                    version.setPresentOnServer(str(fv.presentOnServer))
                    version.setLastModified(str(fv.lastModified))

                    files.append(version)

            if code == 200:
                print('Got file history successfully.')
            else:
                print('Error on getting history (Code: %s)!' % (code))

        else:
            print('Request failed.')

        return files
    def getFileHistory(filename):
        from SugarSyncFile import SugarSyncFile
        sync = SugarSyncInstance.instance

        response = sync.sendRequest('/file/%s/version' % filename, {}, True, False)
        files = None

        if response is not False and response is not None:
            info = response.info()
            code = response.getcode()
            data = XMLElement.parse(response.read().decode('utf8'))

            # We will parse into SugarSyncFile and then return an dict maybe sorted after
            # lastModified
            if code == 200 and data is not None:
                files = []
                for fv in data.childs:
                    version = SugarSyncFile(fv.ref)
                    version.setSize(fv.size)
                    version.setMediaType(str(fv.mediaType))
                    version.setPresentOnServer(str(fv.presentOnServer))
                    version.setLastModified(str(fv.lastModified))

                    files.append(version)

            if code == 200:
                print('Got file history successfully.')
            else:
                print('Error on getting history (Code: %s)!' % (code))

        else:
            print('Request failed.')

        return files
    def moveFile(self, file, newpath):
        data = XMLElement('file')
        data.setHead(self.xmlHead)
        newpath = self.apiURL + '/folder/%s' % newpath

        data.addChild(XMLElement('parent').addChild(XMLTextNode(newpath)))

        resp, content = self.sendRequestPut('/file/%s' % file, data.toString())

        if resp is not None:
            if int(resp['status']) == 200:
                print('File moved.')
            else:
                print('File could not be moved (Code: %s)!' % (resp['status']))
    def renameFile(self, path, newname):
        data = XMLElement('file')
        data.setHead(self.xmlHead)

        data.addChild(XMLElement('displayName').addChild(XMLTextNode(newname)))

        resp, content = self.sendRequestPut('/file/%s' % path, data.toString())

        if resp is not None:
            if int(resp['status']) == 200:
                print('File renamed.')
            else:
                print('File could not be renamed (Code: %s)!' %
                      (resp['status']))
    def getUser(self): 
        response = self.sendRequest('/user', {}, True, False)

        if response is not None:
            resp = XMLElement.parse(response.read().decode('utf8'))
            self.username = str(resp.username)
            self.nickname = str(resp.nickname)
            self.quotaLimit = resp.quota.limit
            self.quotaUsage = resp.quota.usage
            print("Username:\t", self.username)
            print("Nickname:\t", self.nickname)
            print("Space Limit:\t", self.quotaLimit, "Bytes")
            print("Space Used:\t", self.quotaUsage, "Bytes\n")
    def copyFile(self, source, target, name):
        print(source, target, name)
        data = XMLElement('fileCopy')
        data.setHead(self.xmlHead)
        data.setAttribute('source', self.apiURL + '/file/' + source)
        data.addChild(XMLElement('displayName').addChild(XMLTextNode(name)))

        response = self.sendRequest('/folder/%s' % target, data.toString())

        if response is not None:
            info = response.info()
            code = response.getcode()
            location = info['Location']

            if code == 201:
                self.addElementToDatabase('%s/%s' % (target, name), location)
                print('File copied with sucess. Location: %s' % location)
                return True
            else:
                print('File could not be copied (Code: %s)!' % (code))

            return False
    def getUser(self):
        response = self.sendRequest('/user', {}, True, False)

        if response is not None:
            resp = XMLElement.parse(response.read().decode('utf8'))
            self.username = str(resp.username)
            self.nickname = str(resp.nickname)
            self.quotaLimit = resp.quota.limit
            self.quotaUsage = resp.quota.usage
            print("Username:\t", self.username)
            print("Nickname:\t", self.nickname)
            print("Space Limit:\t", self.quotaLimit, "Bytes")
            print("Space Used:\t", self.quotaUsage, "Bytes\n")
    def createFolder(self, path, foldername):
        data = XMLElement('folder')
        data.setHead(self.xmlHead)

        data.addChild(
            XMLElement('displayName').addChild(XMLTextNode(foldername)))

        response = self.sendRequest('/folder/%s' % path, data.toString())

        if response is not None:
            info = response.info()
            code = response.getcode()
            location = info['Location']
            if code == 201:
                self.addElementToDatabase('%s/%s' % (path, foldername),
                                          location)
                print('Folder created with success. Location: %s' % location)
            else:
                print('Folder could not be deleted (Code: %s)!' % (code))
    def renameFolder(self, path, newfolder):
        data = XMLElement('folder')
        data.setHead(self.xmlHead)

        data.addChild(XMLElement('displayName').addChild(XMLTextNode(newfolder)))

        resp, content = self.sendRequestPut('/folder/%s' % path, data.toString())

        if resp is not None:
            if int(resp['status']) == 204:
                print('Folder renamed.')
            else:
                print('Folder could not be renamed (Code: %s)!' % (resp['status']))
    def createFile(self, path, filename, media):
        location = None
        data = XMLElement('file')
        data.setHead(self.xmlHead)

        data.addChild(XMLElement('displayName').addChild(XMLTextNode(filename)))
        data.addChild(XMLElement('mediaType').addChild(XMLTextNode(media)))

        response = self.sendRequest('/folder/%s' % path, data.toString(), False)
        if response is not None:
            info = response.info()
            code = response.getcode()
            location = info['Location']
            if code == 201:
                self.addElementToDatabase('%s/%s' % (path, filename), location)
                print('File created with success. Location: %s' % location)
            else:
                print('File could not be deleted (Code: %s)!' % (code))

        return location
    def moveFile(self, file, newpath):
        data = XMLElement('file')
        data.setHead(self.xmlHead)
        newpath = self.apiURL + '/folder/%s' % newpath

        data.addChild(XMLElement('parent').addChild(XMLTextNode(newpath)))

        resp, content = self.sendRequestPut('/file/%s' % file, data.toString())
        
        if resp is not None:
            if int(resp['status']) == 200:
                print('File moved.')
            else:
                print('File could not be moved (Code: %s)!' % (resp['status']))
    def getFolderInfo(foldername): # foldername is the id
        sync = SugarSyncInstance.instance

        resp = sync.sendRequest('/folder/'+foldername, post=False)
        respData = None

        if resp is not None:
            if int(resp.status) == 200:
                print('Received successful.')
                # data.. but in which method?
                data = resp.read().decode('utf8')
                respData = XMLElement.parse(data)

            else:
                print('Folder Informations could not be retrieved. (Code: %s)' % resp.status)

        else:
            print('Could not retrieve folder informations.')
        
        return respData
    def copyFile(self, source, target, name):
        print(source, target, name)
        data = XMLElement('fileCopy')
        data.setHead(self.xmlHead)
        data.setAttribute('source', self.apiURL+'/file/'+source)
        data.addChild(XMLElement('displayName').addChild(XMLTextNode(name)))

        response = self.sendRequest('/folder/%s' % target, data.toString())
        
        if response is not None:
            info = response.info()
            code = response.getcode()
            location = info['Location']

            if code == 201:
                self.addElementToDatabase('%s/%s' % (target, name), location)
                print('File copied with sucess. Location: %s' % location)
                return True
            else:
                print('File could not be copied (Code: %s)!' % (code))

            return False
 def getAllFilesCollection(self):
     response = self.sendRequest('/user', {}, True, False)
     
     if response is not None:
         data = XMLElement.parse(response.read().decode('utf8'))
         self.quotaLimit = data.quota.limit
         self.quotaUsage = data.quota.usage
     
         self.folder['workspaces'] = data.workspaces
         self.folder['syncfolders'] = data.syncfolders
         self.folder['deleted'] = data.deleted
         self.folder['magicBriefcase'] = data.magicBriefcase
         self.folder['webArchive'] = data.webArchive
         self.folder['mobilePhotos'] = data.mobilePhotos
         self.folder['albums'] = data.albums
         self.folder['recentactivities'] = data.recentActivities
         self.folder['receivedshares'] = data.receivedShares
         self.folder['publiclinks'] = data.publicLinks
     
         print("Data loaded! \n\n")
    def getAllFilesCollection(self):
        response = self.sendRequest('/user', {}, True, False)

        if response is not None:
            data = XMLElement.parse(response.read().decode('utf8'))
            self.quotaLimit = data.quota.limit
            self.quotaUsage = data.quota.usage

            self.folder['workspaces'] = data.workspaces
            self.folder['syncfolders'] = data.syncfolders
            self.folder['deleted'] = data.deleted
            self.folder['magicBriefcase'] = data.magicBriefcase
            self.folder['webArchive'] = data.webArchive
            self.folder['mobilePhotos'] = data.mobilePhotos
            self.folder['albums'] = data.albums
            self.folder['recentactivities'] = data.recentActivities
            self.folder['receivedshares'] = data.receivedShares
            self.folder['publiclinks'] = data.publicLinks

            print("Data loaded! \n\n")
    def getFolderInfo(foldername):  # foldername is the id
        sync = SugarSyncInstance.instance

        resp = sync.sendRequest('/folder/' + foldername, post=False)
        respData = None

        if resp is not None:
            if int(resp.status) == 200:
                print('Received successful.')
                # data.. but in which method?
                data = resp.read().decode('utf8')
                respData = XMLElement.parse(data)

            else:
                print(
                    'Folder Informations could not be retrieved. (Code: %s)' %
                    resp.status)

        else:
            print('Could not retrieve folder informations.')

        return respData
    def createFolder(self, path, foldername):
        data = XMLElement('folder')
        data.setHead(self.xmlHead)

        data.addChild(XMLElement('displayName').addChild(XMLTextNode(foldername)))

        response = self.sendRequest('/folder/%s' % path, data.toString())

        if response is not None:
            info = response.info()
            code = response.getcode()
            location = info['Location']
            if code == 201:
                self.addElementToDatabase('%s/%s' % (path, foldername), location)
                print('Folder created with success. Location: %s' % location)
            else:
                print('Folder could not be deleted (Code: %s)!' % (code))
    def getFileInfo(filename, absolut=False): # filename => file id
        sync = SugarSyncInstance.instance

        if absolut is False:
            filename = '/file/' + filename

        resp = sync.sendRequest(filename, post=False)
        respData = None

        if resp is not None:
            if int(resp.status) == 200:
                print('Received successful.')
                # data.. but in which method?
                data = resp.read().decode('utf8')
                respData = XMLElement.parse(data)

            else:
                print('File informations could not be retrieved. (Code: %s)' % resp.status)

        else:
            print('Could not retrieve file informations.')
        
        return respData
    def getFileInfo(filename, absolut=False):  # filename => file id
        sync = SugarSyncInstance.instance

        if absolut is False:
            filename = '/file/' + filename

        resp = sync.sendRequest(filename, post=False)
        respData = None

        if resp is not None:
            if int(resp.status) == 200:
                print('Received successful.')
                # data.. but in which method?
                data = resp.read().decode('utf8')
                respData = XMLElement.parse(data)

            else:
                print('File informations could not be retrieved. (Code: %s)' %
                      resp.status)

        else:
            print('Could not retrieve file informations.')

        return respData
    def parse(xml, parse = True, first = True):
        xmlpar = []
        if parse:
            # we remove all \n and others!
            xml = re.sub('\n', '', xml)
            xml = re.sub('\r', '', xml)
            xml = re.sub('>( *)<', '><', xml)

            tree = dom.parseString(xml)
            # we have always to use the first child!
            return XMLParser.parse(tree, False)
        else:
            tree = xml

        for branch in tree.childNodes:
            if branch.nodeType == branch.ELEMENT_NODE:
                xmltmp = XMLElement(branch.nodeName)
                # Attribute ?
                if branch._get_attributes() is not None:
                    for attr,value in branch._get_attributes().items():
                        xmltmp.setAttribute(attr,value)

                if branch.childNodes is not None:
                    ch = XMLParser.parse(branch, False, False)
                    if ch is not None:
                        for child in ch:
                            xmltmp.addChild(child)

                xmlpar.append(xmltmp)
            elif branch.nodeType == branch.TEXT_NODE:
                xmlpar.append(XMLTextNode(branch.nodeValue))
            else:
                xmlpar = None

        if first and xmlpar is not None and len(xmlpar) == 1:
            xmlpar = xmlpar[0]

        return xmlpar
    def updateFile(self, filename, name = '', mediaType = '', parent = ''):
        resp = None
        content = None

        if parent != '':
            parent = self.apiURL + '/folder/%s' % parent

        if parent != '' or name != '' or mediaType != '':
            data = XMLElement('file')
            data.setHead(self.xmlHead)

            if name != '':
                data.addChild(XMLElement('displayName').addChild(XMLTextNode(name)))

            if mediaType != '':
                data.addChild(XMLElement('mediaType').addChild(XMLTextNode(mediaType)))

            if parent != '':
                data.addChild(XMLElement('parent').addChild(XMLTextNode(parent)))

            resp, content = self.sendRequestPut('/file/%s' % filename, data.toString())

            if resp is not None:
                if int(resp['status']) == 200:
                    content = XMLElement.parse(content) # here are the file infos ;-)

                    print('File Information updated')
                else:
                    print('File information could not be updated (Code: %s)!' % (resp['status']))
        else:
            print('There is nothing to change O_o')
    def setPublicLink(self, filename, create=True):
        resp = None
        content = None

        data = XMLElement('file')
        data.setHead(self.xmlHead)

        elm = XMLElement('publicLink')
        if create:
            elm.setAttribute('enabled', 'true')
        else:
            elm.setAttribute('enabled', 'false')

        data.addChild(elm)

        resp, content = self.sendRequestPut('/file/%s' % filename,
                                            data.toString())

        if resp is not None:
            if int(resp['status']) == 200:
                content = XMLElement.parse(content)
                if create:
                    print('Created public link: %s' % content.publicLink)
                else:
                    print('Public link destroyed successful.')
            else:
                print('Could not create/destroy public link (Code: %s).' %
                      resp['status'])
        else:
            print('Could not create/destroy public link (request failed).')
    def setPublicLink(self, filename, create=True):
        resp = None
        content = None

        data = XMLElement('file')
        data.setHead(self.xmlHead)
        
        elm = XMLElement('publicLink')
        if create:
            elm.setAttribute('enabled', 'true')
        else:
            elm.setAttribute('enabled', 'false')

        data.addChild(elm)

        resp, content = self.sendRequestPut('/file/%s' % filename, data.toString())

        if resp is not None:
            if int(resp['status']) == 200:
                content = XMLElement.parse(content)
                if create:
                    print('Created public link: %s' % content.publicLink)
                else: 
                    print('Public link destroyed successful.')
            else:
                print('Could not create/destroy public link (Code: %s).' % resp['status'])
        else:
            print('Could not create/destroy public link (request failed).')
    def updateFile(self, filename, name='', mediaType='', parent=''):
        resp = None
        content = None

        if parent != '':
            parent = self.apiURL + '/folder/%s' % parent

        if parent != '' or name != '' or mediaType != '':
            data = XMLElement('file')
            data.setHead(self.xmlHead)

            if name != '':
                data.addChild(
                    XMLElement('displayName').addChild(XMLTextNode(name)))

            if mediaType != '':
                data.addChild(
                    XMLElement('mediaType').addChild(XMLTextNode(mediaType)))

            if parent != '':
                data.addChild(
                    XMLElement('parent').addChild(XMLTextNode(parent)))

            resp, content = self.sendRequestPut('/file/%s' % filename,
                                                data.toString())

            if resp is not None:
                if int(resp['status']) == 200:
                    content = XMLElement.parse(
                        content)  # here are the file infos ;-)

                    print('File Information updated')
                else:
                    print('File information could not be updated (Code: %s)!' %
                          (resp['status']))
        else:
            print('There is nothing to change O_o')
    def auth(self):
        data = XMLElement('authRequest')
        data.setHead(self.xmlHead)

        data.addChild(XMLElement('username').addChild(XMLTextNode(self.username)))
        data.addChild(XMLElement('password').addChild(XMLTextNode(self.password)))
        data.addChild(XMLElement('accessKeyId').addChild(XMLTextNode(self.accessKeyId)))
        data.addChild(XMLElement('privateAccessKey').addChild(XMLTextNode(self.privateAccessKey)))
        
        response = self.sendRequest('/authorization', data.toString(), False)
        if response is not None:
            info = response.info()
            self.token = info['Location']
            resp = XMLElement.parse(response.read().decode('utf8'))
            self.tokenExpire = resp.expiration
            # get the user info
            self.getUser()
    def auth(self):
        data = XMLElement('authRequest')
        data.setHead(self.xmlHead)

        data.addChild(
            XMLElement('username').addChild(XMLTextNode(self.username)))
        data.addChild(
            XMLElement('password').addChild(XMLTextNode(self.password)))
        data.addChild(
            XMLElement('accessKeyId').addChild(XMLTextNode(self.accessKeyId)))
        data.addChild(
            XMLElement('privateAccessKey').addChild(
                XMLTextNode(self.privateAccessKey)))

        response = self.sendRequest('/authorization', data.toString(), False)
        if response is not None:
            info = response.info()
            self.token = info['Location']
            resp = XMLElement.parse(response.read().decode('utf8'))
            self.tokenExpire = resp.expiration
            # get the user info
            self.getUser()
    def createFile(self, path, filename, media):
        location = None
        data = XMLElement('file')
        data.setHead(self.xmlHead)

        data.addChild(
            XMLElement('displayName').addChild(XMLTextNode(filename)))
        data.addChild(XMLElement('mediaType').addChild(XMLTextNode(media)))

        response = self.sendRequest('/folder/%s' % path, data.toString(),
                                    False)
        if response is not None:
            info = response.info()
            code = response.getcode()
            location = info['Location']
            if code == 201:
                self.addElementToDatabase('%s/%s' % (path, filename), location)
                print('File created with success. Location: %s' % location)
            else:
                print('File could not be deleted (Code: %s)!' % (code))

        return location