Example #1
0
def upload(filepath=None, replace=False):

    if not filepath:
        parser = argparse.ArgumentParser(
            "Upload Goosepaper to reMarkable tablet")
        parser.add_argument(
            "file",
            default=None,
            help="The file to upload",
        )
        args = parser.parse_args()
        filepath = args.file

    filepath = Path(filepath)

    client = Client()

    try:
        client.renew_token()
    except AuthError:
        print(
            "Looks like this if the first time you've uploaded, need to register the device"
        )
        print(
            "Get the code from here: https://my.remarkable.com/connect/remarkable"
        )
        code = input()
        print("registering")
        client.register_device(code)
        if not client.renew_token():
            print("registration failed D:")
        else:
            print("registration successful")

    for item in client.get_meta_items():
        if item.VissibleName == filepath.stem:
            if replace:
                client.delete(item)
            else:
                print("Honk! Paper already exists!")
                return False

    doc = ZipDocument(doc=str(filepath.resolve()))
    if client.upload(doc):
        print("Honk! Upload successful!")
    else:
        print("Honk! Error with upload!")

    return True
Example #2
0
def auth_client():
    client = Client()

    try:
        client.renew_token()
    except AuthError:
        print("Looks like this is the first time you've uploaded. You need to "
              f"register the device. Input a code from {CODE_URL}")
        code = input()
        print("registering")
        client.register_device(code)
        if not client.renew_token():
            print("Honk! Registration renewal failed.")
            return False
        else:
            print("registration successful")

    return client
Example #3
0
def auth_client():
    client = Client()

    try:
        client.renew_token()
    except AuthError:
        print(
            "Looks like this if the first time you've uploaded, need to register the device"
        )
        print("Get the code from here: https://my.remarkable.com/connect/remarkable")
        code = input()
        print("registering")
        client.register_device(code)
        if not client.renew_token():
            print("Honk! Registration failed D:")
            return False
        else:
            print("registration successful")

    return client
Example #4
0
def register_user(user_email: str, code: str):
    rm = Client()
    rm.register_device(code, save_to_file=False)
    new_cfg = rm.renew_token(save_to_file=False)
    set_config_for_user(user_email, new_cfg)
    return True
Example #5
0
# Start logging stuff
logger = log.setup_logger(__name__)

rmapy = Client()
# This registers the client as a new device. The received device token is
# stored in the users directory in the file ~/.rmapi, the same as with the
# go rmapi client.
home = os.path.expanduser("~")
if os.path.exists(home + "/.rmapi"):
    if rmapy.is_auth():
        print(
            "Your Device is already authorized. If you believe this is incorrect, delete ~/.rmapi in your home directory and try to register again."
        )
    elif rmapy.renew_token():
        print("Token renewed!")
    else:
        logger.warning(
            "error occured while registering. ~./rmapi token exists, but another token is not able to renew."
        )
else:
    print(
        "Go to my reMarkable (https://my.remarkable.com/connect/desktop) to register a new device and enter the code returned after registering:"
    )
    rmapy.register_device(input())
    # It's always a good idea to renew the user token every time you start
    # a new session.
    rmapy.renew_token()
    if rmapy.is_auth():
        logger.warning("Registration completed successfully.")
import sys
from rmapy.api import Client

rmapy_client = Client()
if not rmapy_client.is_auth():
    rmapy_client.register_device(sys.argv[1])
class RemarkableDelivery(DeliveryMethod):
    """Delivery method class for the ReMarkable tablet."""
    def __init__(self):
        """Initialize the class by connecting the user to the ReMarkable cloud."""
        self.client = Client()

        if not self.client.is_auth():
            click.confirm(
                "We will need to register with the ReMarkable cloud. \
Please confirm that we may open a webpage.",
                abort=True,
            )
            click.launch("https://my.remarkable.com/connect/remarkable")

            device_token = click.prompt("Please enter the device token below")
            self.client.register_device(device_token)

        self.client.renew_token()

    def __str__(self):
        """Return a readable representation of the RemarkableDelivery class.

        :return: The display name of this class.
            Used when choosing this class from a list of options.
        """
        return "ReMarkable"

    @staticmethod
    def convert_issue_to_pdf(book_path: str) -> str:
        """Convert an epub book file to a pdf format for the remarkable. \
            Uses calibre command line utility `ebook-convert`.

        :param book_path: The absolute path to the epub file.
        :raises RuntimeError: Raises exception when calibre
            command line tools are not installed.
        :return: The absolute path to the converted pdf file.
        """
        book_directory = os.path.dirname(book_path)
        pdf_path = os.path.join(book_directory, "./issue.pdf")
        exit_code = os.system(f"ebook-convert {book_path} {pdf_path}")

        if exit_code == 32512:
            # Try macOS location
            exit_code = os.system(
                f"/Applications/calibre.app/Contents/MacOS/ebook-convert {book_path} {pdf_path}"
            )
            if exit_code == 32512:
                raise RuntimeError(
                    "Calibre command line tools are not installed. \
Install from https://calibre-ebook.com")

        return pdf_path

    def deliver_issue(self, absolute_path: str):
        """Deliver issues to the ReMarkable.

        :param absolute_path: An absolute path for the epub file.
        """
        # Ensure a "News Assistant" folder exists
        collection = self.client.get_meta_items()
        root_folders = [
            f for f in collection if isinstance(f, Folder) and f.Parent == ""
        ]

        delivery_folder_filter = [
            f for f in root_folders if f.VissibleName == DELIVERY_FOLDER
        ]
        if len(delivery_folder_filter) == 0:
            folder = Folder(DELIVERY_FOLDER)
            self.client.create_folder(folder)
            delivery_folder_filter.append(folder)

        delivery_folder = delivery_folder_filter[0]

        # Upload the issue
        pdf_path = RemarkableDelivery.convert_issue_to_pdf(absolute_path)
        document = ZipDocument(doc=pdf_path)
        now = datetime.now()
        document.metadata["VissibleName"] = now.strftime("%d %B, %Y")
        self.client.upload(document, delivery_folder)