Exemplo n.º 1
0
def sync(localDeckID, serverURL, username, password, firsttime=True):
    """Syncronice a local deck with a remote deck."""
    col = mw.col
    col.flush()
    # Create a Server handle to send the requests to
    server = connectionHandler(serverURL, username, password)
    col = mw.col
    print("Starting sync")
    # Create a Deck object from the localDeckID
    localDeckToPush = AnkipubSubDeck.fromLocalID(localDeckID)
    # Check if we have a RemoteId for the deck
    # if not we assume the Deck doesnt exist on the server
    if not localDeckToPush.getRemoteID():

        print("The deck with the {0} did not have a RemoteId\
         so we push it to the server".format(localDeckID))
        # copy that stuff because server.push push does conversion magic
        remoteDeck = server.push_deck(localDeckToPush)
        """deepcopy that bitch because of conversion magic in serverupdate\
        UserDict-->Json and not back todo maybe do this in serverupdate not\
         sure but for now f**k it"""

        print('write new entry to DeckIDs RemoteId\
         = {0} localid = {1}'.format(remoteDeck.getRemoteID(), localDeckID))

        remoteDeck.save(mw.col, serverURL)
    else:  # deck exists
        print('The we are trying to sync\
        has following remote ID {0}'.format(localDeckToPush.getRemoteID()))
        """We pull the Deck from the Server to check if there\
         where any changes done"""
        remoteDeckPull = server.pull_deck(localDeckToPush.getRemoteID())
        """If the Date from the last Change on the Server is newer then the\
         Date we wrote in our Database local"""
        #
        print('Last Change on the Server\
         Deck {0}'.format(remoteDeckPull.getLastChange()))
        print('Last Change on the Local\
         Deck {0}'.format(localDeckToPush.getLastChange()))

        newNotes = False
        for note in localDeckToPush.getNotes():
            if not note.getRemoteID():
                newNotes = True

        if (remoteDeckPull.getLastChange() >
                localDeckToPush.getLastChange()) and firsttime:
            print('Deck on the Server is newer so we pull the deck')
            remoteDeckPull.save(col, serverURL)
            sync(localDeckID, serverURL, username, password, False)
            # We call sync again to push the local changes we made
        elif (newNotes):
            print('We have a newer deck so we push to the server')
            remoteDeckPush = server.push_deck(localDeckToPush)
            remoteDeckPush.save(col, serverURL)
        else:
            print(
                'We have not added new Notes and the Server has no new notes for us so we dont do anything'
            )
Exemplo n.º 2
0
def upload(localDeckID, serverURL, username, password):
    localDeckToPush = AnkipubSubDeck.fromLocalID(localDeckID)
    server = connectionHandler(serverURL, username, password)
    try:
        remoteDeck = server.push_deck(localDeckToPush)
        remoteDeck.save(mw.col, serverURL)
    except (AuthError, NotFoundError) as e:
        showInfo(e.message)
Exemplo n.º 3
0
def publishDeck(localDeckID, name, serverURL, username, password, readingPassword=None, writingPassword=None):
    localDeckToPush = AnkipubSubDeck.fromLocalID(localDeckID)
    server = connectionHandler(serverURL, username, password)
    try:
        remoteDeck = server.push_deck(localDeckToPush)
        remoteDeck.save(mw.col, serverURL)
    except (AuthError, NotFoundError) as e:
        showInfo(e.message)
Exemplo n.º 4
0
def download(localDeckID, serverURL, username, password):
    localDeckToPush = AnkipubSubDeck.fromLocalID(localDeckID)
    server = connectionHandler(serverURL, username, password)
    try:
        remoteDeckPull = server.pull_deck(localDeckToPush.getRemoteID())
        remoteDeckPull.save(mw.col, serverURL)
    except (AuthError, NotFoundError) as e:
        showInfo(e.message)
Exemplo n.º 5
0
    def push_deck(self, deck, writepassword=None):
        """
        Push the passed deck to the server.

        Take the passed deck transform the models and notes to clean python
        dictionarys, because as an object they are a UserDict which
        can not be converted to json easily
        """
        deck = deepcopy(deck)
        self.login()  # Führe login durch

        notes = deck.get('notes')
        models = deck.get('models')

        for note in notes:
            notes[notes.index(note)] = note.data
        for model in models:
            models[models.index(model)] = model.data
        deck.update({'notes': notes, 'models': models})
        deck.setLastChange(str(deck.getLastChange()))

        # payload für die post request
        payload = deck.data

        # Content Header damit der Server weiß was kommt
        headers = {'content-type': 'application/json'}
        """wenn das deck schon eine ID hat dann wird an diese ID geschickt\
         wenn nicht an den normalen Handler"""
        if deck.getRemoteID():
            url = self.url + "/push/deck/" + deck.getRemoteID()
        else:
            url = self.url + "/push/deck"

        # Führe Post aus
        deckResponse = self.session.post(url,
                                         data=json.dumps(payload),
                                         headers=headers,
                                         auth=(writepassword, ''))
        if not deckResponse.status_code == requests.codes.ok:
            if deckResponse.status_code == 401:
                raise AuthError(
                    deckResponse.json().get('error').get('message'))
            elif deckResponse.status_code == 404:
                raise NotFoundError(
                    deckResponse.json().get('error').get('message'))

        deck = AnkipubSubDeck.fromJsonObject(deckResponse.json())

        self.logout()
        newNotes = []
        newModels = []
        for note in deck.getNotes():
            newNotes.append(AnkipubSubNote(note))
        deck.update({'notes': newNotes})
        for model in deck.get('models'):
            newModels.append(AnkipubSubModel(model))
        deck.update({'models': newModels})
        return deck
Exemplo n.º 6
0
def sync(localDeckID, serverURL, username, password, firsttime=True):
    """Syncronice a local deck with a remote deck."""
    col = mw.col
    col.flush()
    # Create a Server handle to send the requests to
    server = connectionHandler(serverURL, username, password)
    col = mw.col
    print("Starting sync")
    # Create a Deck object from the localDeckID
    localDeckToPush = AnkipubSubDeck.fromLocalID(localDeckID)
    # Check if we have a RemoteId for the deck
    # if not we assume the Deck doesnt exist on the server
    if not localDeckToPush.getRemoteID():

        print("The deck with the {0} did not have a RemoteId\
         so we push it to the server".format(localDeckID))
        # copy that stuff because server.push push does conversion magic
        remoteDeck = server.push_deck(localDeckToPush)

        """deepcopy that bitch because of conversion magic in serverupdate\
        UserDict-->Json and not back todo maybe do this in serverupdate not\
         sure but for now f**k it"""

        print('write new entry to DeckIDs RemoteId\
         = {0} localid = {1}'.format(remoteDeck.getRemoteID(), localDeckID))

        remoteDeck.save(mw.col, serverURL)
    else:  # deck exists
        print('The we are trying to sync\
        has following remote ID {0}'.format(localDeckToPush.getRemoteID()))
        """We pull the Deck from the Server to check if there\
         where any changes done"""
        remoteDeckPull = server.pull_deck(localDeckToPush.getRemoteID())
        """If the Date from the last Change on the Server is newer then the\
         Date we wrote in our Database local"""
        #
        print('Last Change on the Server\
         Deck {0}'.format(remoteDeckPull.getLastChange()))
        print('Last Change on the Local\
         Deck {0}'.format(localDeckToPush.getLastChange()))

        newNotes = False
        for note in localDeckToPush.getNotes():
            if not note.getRemoteID():
                newNotes = True

        if (remoteDeckPull.getLastChange() > localDeckToPush.getLastChange()) and firsttime:
            print('Deck on the Server is newer so we pull the deck')
            remoteDeckPull.save(col, serverURL)
            sync(localDeckID, serverURL, username, password, False)
            # We call sync again to push the local changes we made
        elif(newNotes):
            print('We have a newer deck so we push to the server')
            remoteDeckPush = server.push_deck(localDeckToPush)
            remoteDeckPush.save(col, serverURL)
        else:
            print('We have not added new Notes and the Server has no new notes for us so we dont do anything')
Exemplo n.º 7
0
    def push_deck(self, deck, writepassword=None):
        """
        Push the passed deck to the server.

        Take the passed deck transform the models and notes to clean python
        dictionarys, because as an object they are a UserDict which
        can not be converted to json easily
        """
        deck = deepcopy(deck)
        self.login()  # Führe login durch

        notes = deck.get('notes')
        models = deck.get('models')

        for note in notes:
            notes[notes.index(note)] = note.data
        for model in models:
            models[models.index(model)] = model.data
        deck.update({'notes': notes, 'models': models})
        deck.setLastChange(str(deck.getLastChange()))

        # payload für die post request
        payload = deck.data

        # Content Header damit der Server weiß was kommt
        headers = {'content-type':  'application/json'}
        """wenn das deck schon eine ID hat dann wird an diese ID geschickt\
         wenn nicht an den normalen Handler"""
        if deck.getRemoteID():
            url = self.url+"/push/deck/"+deck.getRemoteID()
        else:
            url = self.url+"/push/deck"

        # Führe Post aus
        deckResponse = self.session.post(url,
                                         data=json.dumps(payload),
                                         headers=headers,
                                         auth=(writepassword, ''))
        if not deckResponse.status_code == requests.codes.ok:
            if deckResponse.status_code == 401:
                raise AuthError(deckResponse.json().get('error').get('message'))
            elif deckResponse.status_code == 404:
                raise NotFoundError(deckResponse.json().get('error').get('message'))

        deck = AnkipubSubDeck.fromJsonObject(deckResponse.json())

        self.logout()
        newNotes = []
        newModels = []
        for note in deck.getNotes():
            newNotes.append(AnkipubSubNote(note))
        deck.update({'notes': newNotes})
        for model in deck.get('models'):
            newModels.append(AnkipubSubModel(model))
        deck.update({'models': newModels})
        return deck
Exemplo n.º 8
0
def drawTable(f):
    table = f.ui.tableWidget
    decks = util.getAllAnkiPubSubDecks()
    table.setRowCount(len(decks))
    table.setColumnCount(3)
    table.setHorizontalHeaderLabels(['Deck', 'Deck Remote ID', ''])
    table.setColumnWidth(0, 160)
    table.setColumnWidth(1, 200)
    table.setColumnWidth(2, 120)

    for (i, deck) in enumerate(decks):
        did = deck[1]

        deck = AnkipubSubDeck.fromLocalID(did)
        deckRemoteID = deck.getRemoteID()
        widget = QWidget(table)
        btnDelete = QPushButton(widget)
        btnDelete.setGeometry(0, 0, 30, 30)

        btnDelete.setIcon(QIcon('../../addons/pubsub/images/Delete-Resized.jpg'))
        btnDelete.setIconSize(QSize(25, 25))
        btnDelete.clicked.connect(partial(deleteAnkiPubSubDeck,form=f, remoteID=deckRemoteID))
        btnDownload = QPushButton(widget)
        btnDownload.setGeometry(30, 0, 30, 30)
        # TODO FIX TO PARTIAL
        btnDownload.clicked.connect(
            partial(download, did,
                    mw.col.conf.get('ankipubsubServer',
                                    "http://144.76.172.187:5000/v0"),
                    mw.col.conf.get('pubSubName', ""),
                    mw.col.conf.get('pubSubPassword', "")))
        btnDownload.setIcon(QIcon('../../addons/pubsub/images/Download-Resized.jpg'))
        btnDownload.setIconSize(QSize(25, 25))

        btnUpload = QPushButton(widget)
        btnUpload.setGeometry(60, 0, 30, 30)
        btnUpload.setIcon(QIcon('../../addons/pubsub/images/Upload-Resized.jpg'))
        btnUpload.setIconSize(QSize(25, 25))
        btnUpload.clicked.connect(
            partial(upload, did,
                    mw.col.conf.get('ankipubsubServer',
                                    "http://144.76.172.187:5000/v0"),
                    mw.col.conf.get('pubSubName', ""),
                    mw.col.conf.get('pubSubPassword', "")))

        btnSettings = QPushButton(widget)
        btnSettings.setGeometry(90, 0, 30, 30)
        btnSettings.setIcon(QIcon('../../addons/pubsub/images/Settings-Resized.jpg'))
        btnSettings.setIconSize(QSize(25, 25))
        btnSettings.clicked.connect(partial(ankiDeckSettings, did=deckRemoteID))
        table.setCellWidget(i, 2, widget)
        table.setItem(i, 0, QTableWidgetItem(str(deck.getName())))
        table.setItem(i, 1, QTableWidgetItem(str(deck.getRemoteID())))
Exemplo n.º 9
0
    def pull_deck(self, deckid, readpassword=None, **kwargs):
        """
        Pull the deck with the passed deckid from the server.

        This function sends a get request to the server and retrieves the
        the deck with the passed id if the access right are sufficent.
        The passed deck will be converted to AnkipubSub objects
        for better handling during the creation of the cards.
        after the complete conversion a AnkipubSubDeck is returend.
        """
        # Kontrolliere ob zusätzliche Parameter übergeben wurden
        if kwargs:
            payload = kwargs.items()
        else:
            payload = {}

        self.login()  # Login

        # Führe get anfrage aus
        deckResponse = self.session.get(self.url + '/pull/deck/' + deckid,
                                        params=payload,
                                        auth=(readpassword, ''))

        # prüfe ob ne valid anfrage zurück kam
        if not deckResponse.status_code == requests.codes.ok:
            if deckResponse.status_code == 401:
                raise AuthError(
                    deckResponse.json().get('error').get('message'))
            elif deckResponse.status_code == 404:
                raise NotFoundError(
                    deckResponse.json().get('error').get('message'))
        # Erzeuge aus der JSOn antwort ein Deck
        deck = AnkipubSubDeck.fromJsonObject(deckResponse.json())
        """Erzeuge aus den Karten in dieser Antwort AnkipupSub Objecte und\
         ersetze damit die Json Liste"""
        newNotes = []

        for note in deck.getNotes():
            newNotes.append(AnkipubSubNote(note))
        deck.update({'notes': newNotes})
        newModels = []
        for model in deck.get('models'):
            newModels.append(AnkipubSubModel(model))
        deck.update({'models': newModels})

        self.logout()
        return deck
Exemplo n.º 10
0
    def pull_deck(self, deckid, readpassword=None, **kwargs):
        """
        Pull the deck with the passed deckid from the server.

        This function sends a get request to the server and retrieves the
        the deck with the passed id if the access right are sufficent.
        The passed deck will be converted to AnkipubSub objects
        for better handling during the creation of the cards.
        after the complete conversion a AnkipubSubDeck is returend.
        """
        # Kontrolliere ob zusätzliche Parameter übergeben wurden
        if kwargs:
            payload = kwargs.items()
        else:
            payload = {}

        self.login()  # Login

        # Führe get anfrage aus
        deckResponse = self.session.get(self.url+'/pull/deck/'+deckid,
                                        params=payload, auth=(readpassword, ''))

        # prüfe ob ne valid anfrage zurück kam
        if not deckResponse.status_code == requests.codes.ok:
            if deckResponse.status_code == 401:
                raise AuthError(deckResponse.json().get('error').get('message'))
            elif deckResponse.status_code == 404:
                raise NotFoundError(deckResponse.json().get('error').get('message'))
        # Erzeuge aus der JSOn antwort ein Deck
        deck = AnkipubSubDeck.fromJsonObject(deckResponse.json())

        """Erzeuge aus den Karten in dieser Antwort AnkipupSub Objecte und\
         ersetze damit die Json Liste"""
        newNotes = []

        for note in deck.getNotes():
            newNotes.append(AnkipubSubNote(note))
        deck.update({'notes': newNotes})
        newModels = []
        for model in deck.get('models'):
            newModels.append(AnkipubSubModel(model))
        deck.update({'models': newModels})

        self.logout()
        return deck