diff --git a/api.py b/api.py index 7251ac6..d7ee633 100755 --- a/api.py +++ b/api.py @@ -177,3 +177,38 @@ def findId(filesOrRmFile, fileId): if rmFile.id == fileId: return rmFile return None + +def getRmFileFor(fileOrFolderPath): + ''' + Search for given file or folder and return the corresponding RmFile. + + Returns RmFile if file or folder was found. Otherwise None. + ''' + files = fetchFileStructure() + for rmFile in iterateAll(files): + if rmFile.path() == fileOrFolderPath: + return rmFile + return None + +def changeDirectory(targetFolder): + ''' + Navigates to a given folder. + + Raises a RuntimeError in case the given targetFolder cannot be found on the device or is not a folder + ''' + rmFile = getRmFileFor(targetFolder) + if rmFile is None: + raise RuntimeError("Folder {} could not be found on device".format(targetFolder)) + if not rmFile.isFolder: + raise RuntimeError("Given path {} is not a folder on the device".format(targetFolder)) + + requests.post(RM_WEB_UI_URL + "/documents/" + rmFile.id) + +def upload(file): + ''' + Uploads a file given by the provided file handle to the currently selected folder. + ''' + files = {'file': file} + response = requests.post(RM_WEB_UI_URL + "/upload", files=files) + if not response.ok: + raise RuntimeError('Upload failed with status code %d' % (response.status_code)) diff --git a/upload.py b/upload.py new file mode 100755 index 0000000..cf4b0ff --- /dev/null +++ b/upload.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +''' +Upload - Upload either PDFs or ePubs to your remarkable. +''' + + +import api +import argparse +import os + +from sys import stderr + +def printUsageAndExit(): + print('Usage: %s ' % argv[0], file=stderr) + exit(1) + + +if __name__ == '__main__': + ap = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + + ap.add_argument('-t', '--target-folder', help='Folder on your remarkable to put the uploaded files in') + ap.add_argument('file', type=argparse.FileType('rb'), nargs='+') + + args = ap.parse_args() + + try: + api.changeDirectory(args.target_folder) + for file in args.file: + file_name, file_extension = os.path.splitext(file.name) + if file_extension.lower() not in [".pdf", ".epub"]: + print('Only PDFs and ePubs are supported. Skipping {}'.format(file.name)) + continue + print('Uploading {} to {}'.format(file.name, args.target_folder)) + api.upload(file) + print('Successfully uploaded {} to {}'.format(file.name, args.target_folder)) + print('Done!') + except KeyboardInterrupt: + print('Cancelled.') + exit(0) + except Exception as ex: + print('ERROR: %s' % ex, file=stderr) + print(file=stderr) + print('Please make sure your reMarkable is connected to this PC and you have enabled the USB Webinterface in "Settings -> Storage".', file=stderr) + exit(1) + finally: + for file in args.file: + file.close()