├── _version.py ├── .gitignore ├── storageservice.py ├── README.md ├── multidrive.py ├── googledrivestorageservice.py ├── clouddrivestorageservice.py ├── onedrivestorageservice.py └── LICENSE.md /_version.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.1.21" 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Google Drive API Information 2 | google_drive_client_secrets.json 3 | 4 | # Google Drive credentials 5 | google_drive_settings.dat 6 | 7 | # OneDrive API Information 8 | onedrive_client_secrets.json 9 | 10 | # OneDrive Credentials 11 | onedrive_settings.json 12 | 13 | # Cloud Drive API Information 14 | cloud_drive_client_secrets.json 15 | 16 | # Cloud Drive Credentials 17 | cloud_drive_settings.json 18 | -------------------------------------------------------------------------------- /storageservice.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Darryl Tam 2 | 3 | # This file is part of MultiDrive. 4 | 5 | # MultiDrive is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | 10 | # MultiDrive is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | 15 | # You should have received a copy of the GNU General Public License 16 | # along with MultiDrive. If not, see . 17 | 18 | from abc import ABCMeta, abstractmethod 19 | 20 | 21 | class StorageService(object): 22 | __metaclass__ = ABCMeta 23 | 24 | @abstractmethod 25 | def authorize(self): 26 | pass 27 | 28 | @abstractmethod 29 | def upload(self, file_path, destination=None, 30 | modified_time=None, create_folder=False, overwrite=False): 31 | pass 32 | 33 | @abstractmethod 34 | def download(self, file_path, destination=None, overwrite=False): 35 | pass 36 | 37 | @abstractmethod 38 | def download_item(self, cur_file, destination=None, 39 | overwrite=False, create_folder=False): 40 | pass 41 | 42 | @abstractmethod 43 | def create_folder(self, folder_path): 44 | pass 45 | 46 | @abstractmethod 47 | def is_folder(self, folder_path): 48 | pass 49 | 50 | @abstractmethod 51 | def list_folder(self, folder_path): 52 | pass 53 | 54 | @abstractmethod 55 | def get_file_name(self, file): 56 | pass 57 | 58 | @abstractmethod 59 | def is_folder_from_file_type(self, file): 60 | pass 61 | 62 | @abstractmethod 63 | def get_quota(self): 64 | pass 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #MultiDrive 2 | 3 | 4 | ## Description 5 | 6 | Basic utilities to upload and download from various cloud storage services. 7 | 8 | Support for Amazon Cloud Drive, Google Drive and Microsoft OneDrive upload and download operations are implemented. 9 | 10 | This is in alpha and there may be serious bugs. This has only been tested on Ubuntu, though it should work on Mac OS X. This has not yet been tested in Windows, and may not work in that OS yet without further testing. However, I have received a report that it does work in Windows. 11 | 12 | No API keys are provided. You will need to sign up as a developer with each service providers to get keys. 13 | 14 | Next Planned Features: 15 | 16 | * Cleaned up debug output 17 | * More robust OneDrive uploads 18 | * Progress display for uploads and downloads. 19 | * More robust handling of Hash errors. 20 | 21 | 22 | ## Usage 23 | 24 | ./multidrive -h 25 | 26 | Displays help 27 | 28 | ./multidrive -s googledrive -a upload -l example.txt 29 | 30 | Uploads "example.txt" to the root directory on Google Drive. 31 | 32 | ./multidrive -s googledrive -a upload -l example.txt -r examplefolder 33 | 34 | Uploads "example.txt" to the "examplefolder" directory on Google Drive. 35 | 36 | ./multidrive -s googledrive -a upload -l example.txt -r examplefolder -c 37 | 38 | Uploads "example.txt" to the "examplefolder" directory on Google Drive. It will create the remote folder if necessary 39 | 40 | ./multidrive -s googledrive -a download -r "example.txt" 41 | 42 | Downloads "example.txt" in the root directory of Google Drive to the local computer. 43 | 44 | ./multidrive -s googledrive -d onedrive -a copy -r "Source Folder" -e "Transfers" -c 45 | 46 | Copies the contents of "Source Folder" on Google Drive to the "Transfers" folder on Microsoft OneDrive, creating the remote folder if necessary. The program will get a list of files, then, transfer one file at a time to the other service by downloading it to the local machine, then uploading it again. 47 | 48 | 49 | ## Current Functionality 50 | 51 | 52 | | |Google Drive |OneDrive |Cloud Drive |Dropbox | 53 | |-------------------|---------------|---------------|---------------|---------------| 54 | |**Authentication**| | | | | 55 | |Authenticate user |Yes|Yes|Yes|Pending| 56 | | | | | | | 57 | |**Basic File Operations**| | | | | 58 | |Upload File |Yes|Yes|Yes|Pending| 59 | |Upload Folder |Yes|Yes|Yes|Pending| 60 | |Download File |Yes|Yes|Yes|Pending| 61 | |Download Folder |Yes|Yes|Yes|Pending| 62 | || | | | | 63 | |**Advanced** 64 | |Get Modified Time |Yes|Partial|Partial|Unknown 65 | |Set Modified Time |Yes|No|No|Unknown| 66 | |Local Overwrite |Yes|Yes|Yes|Pending| 67 | |Remote Overwrite |Yes|Yes|Yes|Pending| 68 | |Local Destination Folder |Yes|Yes|Yes|Pending| 69 | |Remote Destination Folder |Yes|Yes|Yes|Pending| 70 | |List Remote Files |Yes|Yes|Yes|Pending| 71 | |Create Remote Folder |Yes|Yes|Yes|Pending| 72 | |List Quota |Yes|Yes|Yes|Pending| 73 | |Delete Remote File |Pending|Pending|Pending|Pending| 74 | |Copy Folders |Yes|Yes|Yes|Pending| 75 | |Verify Files by Hash|Yes|Yes|Yes|Pending| 76 | 77 | ## Updates 78 | 79 | 2015-04-27 0.1.21: Upload command now supports folder upload. 80 | 81 | 2015-04-12 0.1.20: Add additional debug logging. 82 | Add version display to help message 83 | 84 | 2015-04-10 0.1.19: OneDrive: Add additional timeouts and upload status messages. 85 | 86 | 2015-04-09 0.1.18: OneDrive: Can now resume uploads using upload status. 87 | 88 | 2015-04-08 0.1.17: Bug Fix: Fixed logging for OneDrive upload errors 89 | Added timeout to deal with hanging OneDrive downloads. 90 | 91 | 2015-04-08 0.1.16: Bug Fix: Amazon Cloud Drive should work again on 32-bit systems for files larger than 4GiB 92 | Added logging to better handle OneDrive upload errors. 93 | 94 | 2015-04-07 0.1.15: Bug Fix: OneDrive chunk size updated. Should now work for files larger than 7.6GiB (up to 10GiB) 95 | 96 | 2015-04-06 0.1.14: Bug Fix: Google Drive should now resume properly on a Hash Mismatch 97 | 98 | 99 | 2015-04-05 0.1.13: Improved Quota Output for Google Drive and Cloud Drive. 100 | Bug Fix: OneDrive authentication should work again. 101 | OneDrive: Preparation for implementation of AppFolder functionality. On hold while OneDrive API issues examined. 102 | 103 | 2015-04-04 0.1.12: Cloud Drive: Improved Quota Output. Now lists usage for various categories, even if it doesn't use quota. 104 | Bug Fix: OneDrive: If OneDrive server reports that the fragment has already been sent, send the next one. Will need to monitor for this rare issue to see if this can be improved upon. 105 | 106 | 2015-04-04 0.1.11: Update Readme 107 | Bug Fix: Google Drive: ' filename issue should now be fixed properly. 108 | 109 | 2015-04-04 0.1.10: Bug Fix: OneDrive: Fixed debug message for uploads 110 | Bug Fix: Google Drive: Uploads and queries for files with a ' in the name should now work. 111 | 112 | 2015-04-04 0.1.9: New Feature: Quota for each account type can now be listed 113 | 114 | 2015-04-04 0.1.8: Fixed issue with downloading/listing Google Drive folders with more than 100 items. 115 | Minor changes to debug code. 116 | 117 | 2015-04-03 0.1.7: Bug Fix: Cloud Drive HTTP retry code fixed 118 | Additional OneDrive retry code added. 119 | 120 | 2015-04-02 0.1.6: Additional retry code added, particularly on hash and connection failures 121 | Bug Fixes 122 | 123 | 2015-04-02 0.1.5: Attempt Retry on UnicodeDecodeError on Cloud Drive 124 | Fixed Retry code for OneDrive/CloudDrive 125 | Bug Fixes 126 | 127 | 2015-04-01 0.1.4: Added Hash check upon upload and download to confirm files properly transferred. 128 | Bug Fixes 129 | 130 | 131 | 2015-04-01 0.1.3: Refactored Cloud Drive Service class to reduce access token requests and improve http request handling. 132 | Refactored OneDrive HTTP requests for robustness. 133 | Bug Fixes 134 | 135 | 2015-03-31 0.1.2: Refactored OneDrive Service class. It should be faster now, with less requests going to the server. 136 | Bug Fixes 137 | 138 | 2015-03-31 0.1.1: Added debug option (-b) 139 | Bug Fixes 140 | 141 | 2015-03-30 0.1.0: Changed to Python 3 to try to allow 32-bit systems to upload files greater than 4GB in size to Cloud Drive. 142 | Removed PyDrive as it is not supported in Python 3. 143 | Added new authenticaion method for Google Drive due to removal of PyDrive. You'll need to rename the client_secrets.json file to google_drive_client_secrets.json and reauthenticate. 144 | Added prompt to acknowledge risks if malware detected by Google Drive 145 | Bug Fixes 146 | 147 | ## Known issues 148 | 149 | An error may be returned if uploading a file greater than 10GB to Amazon Cloud Drive. A report with Amazon has been filed. The file appears to upload properly after a short delay. 150 | 151 | A possibly related issue is that downloading a file greater than 10GB is not supported from Amazon Cloud Drive. It's unclear if it's currently possible to download these files. 152 | 153 | ## Requirements 154 | 155 | Requires the httplib2, python-dateutil, google-api-python-client, requests, and requests-toolbelt libraries. 156 | 157 | requests-toolbelt version 4.0.0 or later is required for OneDrive uploads. This was released on 2015-04-03. 158 | 159 | google-api-python-client now supports Python 3, though it requires an updated httplib2 module not available in pip. This can be installed from source. 160 | 161 | 162 | This can be installed by running: 163 | wget https://github.com/jcgregorio/httplib2/archive/master.zip 164 | unzip master.zip 165 | cd httplib2-master 166 | python3 ./setup.py install 167 | pip install google-api-python-client 168 | pip install requests 169 | pip install requests-toolbelt 170 | pip install python-dateutil 171 | 172 | 173 | ## Google Drive setup 174 | 175 | Go to https://code.google.com/apis/console with your Google Account. 176 | 177 | Create a new project. 178 | Under API's and Auth, enable the Drive API. 179 | In Credentials: Create a new Client ID for an "Installed Application" 180 | Download the JSON file, put it in the working directory and name it google_drive_client_secrets.json 181 | 182 | Credentials are stored in google_drive_settings.dat after authentication. 183 | 184 | ## OneDrive Setup 185 | 186 | Sign up for API key (TODO: Add instructions) 187 | 188 | Create a file onedrive_client_secrets.json with the following information (insert your client id and secret): 189 | 190 | {"client_id": "000000001234ABCD", "client_secret":"cL1eNtS3cr3T60eSHere01234567890A"} 191 | 192 | ## Cloud Drive Setup. 193 | 194 | Sign up for API key. See https://developer.amazon.com/public/apis/experience/cloud-drive/content/getting-started 195 | 196 | Create a file cloud_drive_client_secrets.json with the following information (insert your client id and secret, as well as your Return URL): 197 | 198 | {"client_id": "amzn1.application-oa2-client.000000001234ABCD", "client_secret":"cL1eNtS3cr3T60eSHere01234567890A", "return_uri":"https://example.com/login"} 199 | 200 | 201 | ## Planned features 202 | Support for Dropbox is planned. 203 | Support for handling quota errors. 204 | When downloading/uploading folders, if overwrite is disabled, check to see if there are any file conflicts before starting operations 205 | Support keeping track of last modified time on platforms that support it (Supported for Google Drive, limited support on Amazon Cloud Drive and Microsoft OneDrive). 206 | Deal with Google's versions feature when overwriting files. 207 | Support for OneDrive's experimental upload from URL feature. This could speed up transfers to OneDrive from other services that provide a public URL for files (Currently just Amazon Cloud Drive and Dropbox. 208 | 209 | ## Licence 210 | 211 | GPL v3 212 | 213 | See licence file for details 214 | 215 | 216 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 217 | 218 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES -------------------------------------------------------------------------------- /multidrive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright (C) 2015 Darryl Tam 5 | 6 | # This file is part of MultiDrive. 7 | 8 | # MultiDrive is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | 13 | # MultiDrive is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | 18 | # You should have received a copy of the GNU General Public License 19 | # along with MultiDrive. If not, see . 20 | 21 | 22 | import argparse 23 | import os 24 | import logging 25 | from googledrivestorageservice import GoogleDriveStorageService 26 | from onedrivestorageservice import OneDriveStorageService 27 | from clouddrivestorageservice import CloudDriveStorageService 28 | import tempfile 29 | import shutil 30 | from _version import __version__ 31 | 32 | 33 | def get_storage_service(service_name): 34 | if service_name.lower() == 'googledrive': 35 | return GoogleDriveStorageService() 36 | elif service_name.lower() == 'onedrive': 37 | return OneDriveStorageService() 38 | elif service_name.lower() == 'clouddrive': 39 | return CloudDriveStorageService() 40 | return None 41 | 42 | 43 | def main(): 44 | parser = argparse.ArgumentParser(description='MultiDrive version ' + 45 | str(__version__) + 46 | '\nMultiple Cloud Storage ' 47 | 'Operations') 48 | parser.add_argument('-s', '--source', nargs=1, required=True, 49 | help='set primary service for this command. Valid ' 50 | 'values are clouddrive, onedrive and googledrive') 51 | parser.add_argument('-a', '--action', nargs=1, required=True, 52 | help='action to perform, valid actions include ' 53 | 'download, upload, list, copy, and quota') 54 | parser.add_argument('-d', '--destination', nargs=1, 55 | help='set secondary service for this command, Valid ' 56 | 'values are clouddrive, onedrive and googledrive. ' 57 | 'Only valid with copy command') 58 | parser.add_argument('-l', '--local', nargs=1, 59 | help='path of local file or folder') 60 | parser.add_argument('-r', '--remote', nargs=1, 61 | help='path of remote file or folder') 62 | parser.add_argument('-c', '--createfolder', 63 | help='enable creation of necessary remote folders', 64 | action='store_true') 65 | parser.add_argument('-e', '--secondaryremote', nargs=1, 66 | help='path secondary remote file or folder (for copy ' 67 | 'action)') 68 | parser.add_argument('-o', '--overwrite', 69 | help='enable overwriting of files', 70 | action='store_true') 71 | parser.add_argument('-b', '--debug', help="enable debug logging", 72 | action='store_true') 73 | 74 | args = parser.parse_args() 75 | 76 | service = get_storage_service(args.source[0]) 77 | if service is None: 78 | raise ValueError("Please specify a valid source service.") 79 | 80 | service.authorize() 81 | if args.debug is True: 82 | logging.getLogger("multidrive").setLevel(logging.DEBUG) 83 | logging.getLogger("multidrive").debug("Logging enabled.") 84 | if args.action[0].lower() == "upload": 85 | if args.local is None: 86 | raise ValueError("Please specify a local file to upload.") 87 | destination = None 88 | if args.remote is not None: 89 | destination = args.remote[0] 90 | if os.path.isdir(args.local[0]): 91 | if destination is not None and service.is_folder(destination) is False: 92 | if args.createfolder is False: 93 | raise ValueError("Non-existant folder necessary but create folder not set.") 94 | service.create_folder(destination) 95 | 96 | base_local_path = args.local[0] 97 | last_part_of_local_path = os.path.basename(os.path.normpath(base_local_path)) 98 | if destination is None: 99 | destination = last_part_of_local_path 100 | else: 101 | destination = destination + '/' + last_part_of_local_path 102 | base_remote_path = destination 103 | if service.is_folder(base_remote_path) is False: 104 | if args.createfolder is False: 105 | raise ValueError("Non-existant folder necessary but create folder not set.") 106 | service.create_folder(base_remote_path) 107 | for (root, dirs, files) in os.walk(base_local_path): 108 | for cur_dir in dirs: 109 | cur_remote_path = base_remote_path+root[len(base_local_path):]+"/"+cur_dir 110 | if service.is_folder(destination) is False: 111 | if args.createfolder is False: 112 | raise ValueError("Non-existant folder necessary but create folder not set.") 113 | service.create_folder(cur_remote_path) 114 | for cur_file in files: 115 | service.upload(os.path.join(root, cur_file), 116 | destination=base_remote_path+root[len(base_local_path):], 117 | create_folder=args.createfolder, 118 | overwrite=args.overwrite) 119 | 120 | 121 | 122 | else: 123 | service.upload(args.local[0], destination=destination, 124 | create_folder=args.createfolder, 125 | overwrite=args.overwrite) 126 | 127 | elif args.action[0].lower() == "download": 128 | if args.remote is None: 129 | raise ValueError("Please specify a remote file or folder to " 130 | "download.") 131 | local_path = None 132 | if args.local is not None: 133 | local_path = args.local[0] 134 | if service.is_folder(args.remote[0]) is True: 135 | # TODO: Give an error earlier if the 136 | # destination folder doesn't exist 137 | remote_files = service.list_folder(args.remote[0]) 138 | for (cur_file, path) in remote_files: 139 | destination = None 140 | if local_path is None: 141 | if path is None or len(path) == 0: 142 | destination = None 143 | else: 144 | # TODO: is is portable to windows? Should I be using a 145 | # "/".join method? 146 | destination = os.path.join(*path) 147 | else: 148 | destination = os.path.join(local_path, *path) 149 | service.download_item(cur_file, 150 | destination=destination, 151 | overwrite=args.overwrite, 152 | create_folder=True) 153 | else: 154 | service.download(args.remote[0], 155 | local_path, 156 | overwrite=args.overwrite) 157 | elif args.action[0].lower() == "list": 158 | if args.remote is None: 159 | raise ValueError("Please specify a remote folder to list.") 160 | if service.is_folder(args.remote[0]) is False: 161 | raise ValueError("Remote path is either does not exist or is not " 162 | "a folder") 163 | for (cur_file, path) in service.list_folder(args.remote[0]): 164 | new_path = list(path) 165 | new_path.append(service.get_file_name(cur_file)) 166 | print("/".join(new_path)) 167 | elif args.action[0].lower() == "copy": 168 | if args.destination is None: 169 | raise ValueError("Please specify a destination for copy " 170 | "operation.") 171 | service2 = get_storage_service(args.destination[0]) 172 | service2.authorize() 173 | if service2 is None: 174 | raise ValueError("Please specify a valid secondary source " 175 | "service.") 176 | if args.source[0].lower() == args.secondaryremote[0].lower(): 177 | raise ValueError("Primary and secondary services must be " 178 | "different") 179 | if args.remote is None: 180 | raise ValueError("Please specify a remote file or folder to copy " 181 | "from.") 182 | if args.secondaryremote is None: 183 | raise ValueError("Please specify a secondary remote file or " 184 | "folder to copy to.") 185 | 186 | if args.createfolder is False and \ 187 | service2.is_folder(args.secondaryremote[0]) \ 188 | is False: 189 | raise ValueError("Secondary remote folder does not exist. Use the " 190 | "createfolder option to create it") 191 | tmp_path = tempfile.mkdtemp() 192 | try: 193 | if service.is_folder(args.remote[0]) is True: 194 | remote_files = service.list_folder(args.remote[0]) 195 | for (cur_file, path) in remote_files: 196 | 197 | cur_dest = args.secondaryremote[0] 198 | if len(path) > 0: 199 | cur_dest = os.path.join(cur_dest, *path) 200 | 201 | if service.is_folder_from_file_type(cur_file): 202 | if not service2.is_folder(cur_dest): 203 | service2.create_folder(cur_dest) 204 | else: 205 | (local_temp, 206 | last_mod) = (service.download_item( 207 | cur_file, 208 | destination=tmp_path, 209 | overwrite=args.overwrite)) 210 | 211 | service2.upload(local_temp, destination=cur_dest, 212 | modified_time=last_mod, 213 | create_folder=args.createfolder, 214 | overwrite=args.overwrite) 215 | os.remove(local_temp) 216 | else: 217 | (local_temp, last_mod) = (service.download( 218 | args.remote[0], tmp_path, 219 | overwrite=args.overwrite)) 220 | service2.upload(local_temp, 221 | destination=args.secondaryremote[0], 222 | modified_time=last_mod, 223 | create_folder=args.createfolder, 224 | overwrite=args.overwrite) 225 | os.remove(local_temp) 226 | finally: 227 | shutil.rmtree(tmp_path) 228 | elif args.action[0].lower() == "quota": 229 | print(service.get_quota()) 230 | else: 231 | raise ValueError("Please specify a valid action.") 232 | 233 | 234 | if __name__ == "__main__": 235 | main() 236 | -------------------------------------------------------------------------------- /googledrivestorageservice.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Darryl Tam 2 | 3 | # This file is part of MultiDrive. 4 | 5 | # MultiDrive is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | 10 | # MultiDrive is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | 15 | # You should have received a copy of the GNU General Public License 16 | # along with MultiDrive. If not, see . 17 | 18 | import requests 19 | import dateutil.parser 20 | import datetime 21 | import os 22 | import json 23 | import logging 24 | from mimetypes import guess_type 25 | import hashlib 26 | 27 | import apiclient 28 | # from apiclient.http import MediaFileUpload 29 | from apiclient.http import MediaIoBaseUpload 30 | 31 | from oauth2client import client 32 | from oauth2client.file import Storage 33 | from apiclient.discovery import build 34 | import httplib2 35 | 36 | import time 37 | 38 | from storageservice import StorageService 39 | 40 | 41 | class HashMismatch(RuntimeError): 42 | pass 43 | 44 | 45 | class HashFile(object): 46 | def set_file(self, cur_file): 47 | self.file = cur_file 48 | self.cur_file_hash = hashlib.md5() 49 | self.begin = False 50 | self.last_hash_pos = 0 51 | if self.file.tell() == 0: 52 | self.begin = True 53 | 54 | pos = self.file.tell() 55 | self.file.seek(0, os.SEEK_END) 56 | self.length = self.file.tell()-pos 57 | self.file.seek(pos, os.SEEK_SET) 58 | 59 | def __len__(self): 60 | return self.length 61 | 62 | def seek(self, offset, whence=os.SEEK_SET): 63 | self.file.seek(offset, whence) 64 | if self.begin is False and self.file.tell() == 0: 65 | self.begin = True 66 | 67 | def tell(self): 68 | return self.file.tell() 69 | 70 | def read(self, *args): 71 | chunk = self.file.read(*args) 72 | if len(chunk) > 0 and self.begin is True: 73 | if self.file.tell()-len(chunk) == self.last_hash_pos: 74 | self.cur_file_hash.update(chunk) 75 | self.last_hash_pos += len(chunk) 76 | return chunk 77 | 78 | def get_md5(self): 79 | if self.last_hash_pos == self.length: 80 | return self.cur_file_hash.hexdigest() 81 | raise RuntimeError("Did not complete hash of file.") 82 | 83 | 84 | class ItemDoesNotExistError(RuntimeError): 85 | pass 86 | 87 | 88 | class UTC(datetime.tzinfo): 89 | """UTC""" 90 | 91 | def utcoffset(self, dt): 92 | return datetime.timedelta(0) 93 | 94 | def tzname(self, dt): 95 | return "UTC" 96 | 97 | def dst(self, dt): 98 | return datetime.timedelta(0) 99 | 100 | 101 | class GoogleDriveStorageService(StorageService): 102 | 103 | def authorize(self): 104 | logger = logging.getLogger("multidrive") 105 | logger.info("Authorize Google Drive Storage Service") 106 | 107 | flow = client.flow_from_clientsecrets( 108 | 'google_drive_client_secrets.json', 109 | scope='https://www.googleapis.com/auth/drive', 110 | redirect_uri='urn:ietf:wg:oauth:2.0:oob') 111 | 112 | storage = Storage('google_drive_settings.dat') 113 | credentials = storage.get() 114 | if credentials is None or credentials.invalid: 115 | url = flow.step1_get_authorize_url() 116 | print("Go to this URL to authorize: {}".format(url)) 117 | response = input("Enter the Token you received: ") 118 | credentials = flow.step2_exchange(response) 119 | storage.put(credentials) 120 | http_auth = credentials.authorize(httplib2.Http()) 121 | self.__credentials__ = credentials 122 | credentials.set_store(storage) 123 | self.__service__ = build('drive', 'v2', http=http_auth) 124 | 125 | def upload(self, file_path, destination=None, modified_time=None, 126 | create_folder=False, overwrite=False): 127 | print("Uploading {} to Google Drive".format(file_path)) 128 | self.upload_file(file_path, folder=destination, 129 | modified_time=modified_time, 130 | create_folder=create_folder, overwrite=overwrite) 131 | print("Upload complete") 132 | 133 | def download(self, file_path, destination=None, overwrite=False): 134 | print("Downloading {} from Google Drive".format(file_path)) 135 | return self.download_file(file_path, destination=destination, 136 | overwrite=overwrite) 137 | print("Download Complete") 138 | 139 | def is_folder(self, folder_path): 140 | if folder_path is None or folder_path == "": 141 | # Interpret as root 142 | return True 143 | try: 144 | self.get_folder(folder_path) 145 | except ItemDoesNotExistError: 146 | return False 147 | 148 | return True 149 | 150 | def list_folder(self, folder_path): 151 | base_folder = None 152 | if folder_path is None or folder_path == "": 153 | base_folder = 'root' 154 | else: 155 | base_folder = self.get_folder(folder_path) 156 | 157 | folder_list = self.get_folder_listing(base_folder, []) 158 | return folder_list 159 | 160 | def get_folder_listing(self, cur_folder, path_list): 161 | 162 | result_list = [] 163 | query = "'{}' in parents and trashed=false ".format(cur_folder) 164 | 165 | file_list = [] 166 | page_token = None 167 | while True: 168 | files = None 169 | if page_token: 170 | files = (self.__service__.files(). 171 | list(q=query, pageToken=page_token).execute()) 172 | else: 173 | files = self.__service__.files().list(q=query).execute() 174 | 175 | file_list.extend(files['items']) 176 | page_token = files.get('nextPageToken') 177 | if not page_token: 178 | break 179 | 180 | file_list.sort(key=lambda cur_file: cur_file['title']) 181 | for cur_file in file_list: 182 | result_list.append((cur_file, path_list)) 183 | if cur_file['mimeType'] == 'application/vnd.google-apps.folder': 184 | new_list = list(path_list) 185 | new_list.append(cur_file['title']) 186 | result_list.extend(self.get_folder_listing(cur_file['id'], 187 | new_list)) 188 | 189 | return result_list 190 | 191 | def download_file(self, file_path, destination=None, overwrite=False): 192 | cur_file = self.get_file(file_path) 193 | return self.download_item(cur_file, destination=destination, 194 | overwrite=overwrite, create_folder=False) 195 | 196 | def download_item(self, cur_file, destination=None, overwrite=False, 197 | create_folder=False): 198 | logger = logging.getLogger("multidrive") 199 | local_path = cur_file['title'] 200 | if destination is not None: 201 | local_path = os.path.join(destination, local_path) 202 | 203 | if cur_file['mimeType'] == "application/vnd.google-apps.folder": 204 | if create_folder is False: 205 | raise RuntimeError("Path is a folder") 206 | if not os.path.exists(local_path): 207 | os.mkdir(local_path) 208 | return (local_path, cur_file['modifiedDate']) 209 | 210 | if os.path.isdir(local_path): 211 | raise RuntimeError("Local destination is a folder") 212 | if overwrite is False and os.path.isfile(local_path): 213 | raise RuntimeError( 214 | "Local file {} exists. Enable overwrite option to continue." 215 | .format(local_path)) 216 | 217 | NUM_ATTEMPTS = 5 218 | cur_attempt = 1 219 | while cur_attempt <= NUM_ATTEMPTS: 220 | fd = open(local_path, 'wb') 221 | try: 222 | self.download_helper(cur_file['id'], fd, cur_file['title'], 223 | cur_file['md5Checksum']) 224 | except HashMismatch: 225 | logger.warning("Hash of downloaded file does " 226 | "not match server. Attempting again") 227 | cur_attempt += 1 228 | continue 229 | finally: 230 | fd.close() 231 | break 232 | if cur_attempt > NUM_ATTEMPTS: 233 | raise RuntimeError("Hash of downloaded file does " 234 | "not match server.") 235 | 236 | modified_date = dateutil.parser.parse(cur_file['modifiedDate']) 237 | os.utime(local_path, (time.mktime(modified_date.timetuple()), 238 | time.mktime(modified_date.timetuple()))) 239 | return (local_path, cur_file['modifiedDate']) 240 | 241 | def download_helper(self, file_id, local_fd, file_name, remote_hash): 242 | now = datetime.datetime.utcnow() + datetime.timedelta(minutes=1) 243 | expiry = self.__credentials__.token_expiry 244 | if now > expiry: 245 | self.__credentials__.refresh(httplib2.Http()) 246 | 247 | headers = {} 248 | self.__credentials__.apply(headers) 249 | url = "https://www.googleapis.com/drive/v2/files/"+file_id 250 | parameters = {'alt': 'media'} 251 | 252 | response = requests.get(url, headers=headers, stream=True, 253 | params=parameters) 254 | 255 | tries = 0 256 | while response.status_code != requests.codes.ok and tries < 6: 257 | if (response.status_code == requests.codes.forbidden): 258 | message = json.loads(response.text) 259 | if 'error' in message and 'errors' in message['error']: 260 | is_malware = False 261 | for cur_error in message['error']['errors']: 262 | if cur_error['reason'] == 'abuse': 263 | is_malware = True 264 | break 265 | if is_malware is True: 266 | print("Error downloading file with name: {}" 267 | .format(file_name)) 268 | answer = input("The file you have selected to " 269 | "download has been flaged as abusive " 270 | "or malware by Google. Do you still " 271 | "want to download? Only do so if you " 272 | "understand the risks. Enter 'y' or " 273 | "'yes' if you wish to do so. ") 274 | if (answer.lower() == 'y' or answer.lower() == 'yes'): 275 | parameters['acknowledgeAbuse'] = 'true' 276 | response = requests.get(url, headers=headers, 277 | stream=True, 278 | params=parameters) 279 | continue 280 | raise RuntimeError("Abusive or malware file detected " 281 | "and not downloaded. Aborting.") 282 | 283 | # If it's not malware, perhaps we need to refresh the " 284 | # "token, so we'll do that on the next iteration 285 | self.__credentials__.refresh(httplib2.Http()) 286 | self.__credentials__.apply(headers) 287 | 288 | tries += 1 289 | print("Save File: Google Drive connection failed Error: " + 290 | response.text) 291 | print("Retry " + str(tries)) 292 | sleep_length = float(1 << tries) / 2 293 | time.sleep(sleep_length) 294 | response = requests.get(url, headers=headers, stream=True, 295 | params=parameters) 296 | 297 | if response.status_code != requests.codes.ok: 298 | raise RuntimeError("Unable to access Google Drive file") 299 | 300 | size = 0 301 | cur_file_hash = hashlib.md5() 302 | for chunk in response.iter_content(chunk_size=5*1024*1024): 303 | if chunk: # filter out keep-alive new chunks 304 | cur_file_hash.update(chunk) 305 | local_fd.write(chunk) 306 | local_fd.flush() 307 | size = size + 1 308 | if size % 100 == 0: 309 | logging.info(str(size*5) + "MB written") 310 | os.fsync(local_fd.fileno()) 311 | 312 | if remote_hash.lower() != cur_file_hash.hexdigest(): 313 | raise HashMismatch("Hash of downloaded file does " 314 | "not match server.") 315 | 316 | def upload_file(self, file_path, folder=None, modified_time=None, 317 | create_folder=False, overwrite=False): 318 | logger = logging.getLogger("multidrive") 319 | 320 | logger.debug("Uploading " + file_path) 321 | file_name = os.path.basename(file_path) 322 | mime_type = guess_type(file_path)[0] 323 | mime_type = mime_type if mime_type else 'application/octet-stream' 324 | 325 | file_size = os.path.getsize(file_path) 326 | 327 | parents = [] 328 | cur_folder = 'root' 329 | if folder is not None: 330 | cur_folder = self.get_folder(folder, create=create_folder) 331 | parents.append({"id": cur_folder}) 332 | 333 | if modified_time is None: 334 | modified_time = datetime.datetime.fromtimestamp( 335 | os.path.getmtime(file_path), 336 | UTC()).isoformat()[:-6] 337 | if '.' not in modified_time: 338 | modified_time += ".000000Z" 339 | else: 340 | modified_time += "Z" 341 | 342 | # OneDrive returns times that happen to lie on the second without 343 | # the microseconds at the end. 344 | if '.' not in modified_time: 345 | modified_time = modified_time.replace("Z", ".000000Z") 346 | logging.debug("Modified time: "+modified_time) 347 | 348 | NUM_ATTEMPTS = 5 349 | cur_attempt = 1 350 | while cur_attempt <= NUM_ATTEMPTS: 351 | with open(file_path, 'rb') as cur_open_file: 352 | 353 | cur_hash_file = HashFile() 354 | cur_hash_file.set_file(cur_open_file) 355 | 356 | media_body = MediaIoBaseUpload(cur_hash_file, 357 | mimetype=mime_type, 358 | chunksize=1024*1024, 359 | resumable=True) 360 | if file_size == 0: 361 | media_body = None 362 | 363 | existing_file = self.get_file_if_exists(file_name, cur_folder) 364 | 365 | try: 366 | if existing_file is not None: 367 | if overwrite is False: 368 | raise RuntimeError("File already exists") 369 | old_file = self.__service__.files().get( 370 | fileId=existing_file['id']).execute() 371 | old_file['modifiedDate'] = modified_time 372 | old_file['title'] = file_name 373 | old_file['mimeType'] = mime_type 374 | old_file['parents'] = parents 375 | new_file = self.__service__.files().update( 376 | fileId=existing_file['id'], 377 | body=old_file, 378 | media_body=media_body).execute() 379 | else: 380 | body = { 381 | 'title': file_name, 382 | 'mimeType': mime_type, 383 | 'parents': parents, 384 | 'modifiedDate': modified_time, 385 | } 386 | new_file = self.__service__.files().insert( 387 | body=body, 388 | media_body=media_body).execute() 389 | 390 | except apiclient.errors.HttpError as error: 391 | print('An error occured uploading file: %s' % error) 392 | return None 393 | logger.info('Calculated MD5 of uploaded file:' + 394 | cur_hash_file.get_md5()) 395 | logger.info('Google Drive Checksum: ' + 396 | new_file['md5Checksum']) 397 | if (cur_hash_file.get_md5() == new_file['md5Checksum']): 398 | break 399 | logger.warning("Hash of downloaded file does " 400 | "not match server. Attempting again") 401 | cur_attempt += 1 402 | 403 | if (cur_hash_file.get_md5() != new_file['md5Checksum']): 404 | raise HashMismatch("Hash of uploaded file does " 405 | "not match server.") 406 | 407 | def get_file_if_exists(self, file_name, folder_id): 408 | escaped_file_name = file_name.replace("'", "\\'") 409 | query = ("'{}' in parents and trashed=false and " 410 | "title='{}'".format(folder_id, escaped_file_name)) 411 | file_list = self.__service__.files().list(q=query).execute()['items'] 412 | if len(file_list) > 1: 413 | raise RuntimeError('Multiple files with name "{}" exist' 414 | .format(file_name)) 415 | elif len(file_list) is 0: 416 | logging.debug("File {} does not exist".format(file_name)) 417 | return None 418 | else: 419 | logging.debug("File {} exists".format(file_name)) 420 | return file_list[0] 421 | 422 | def get_folder(self, folder_path, create=False): 423 | return self.get_file(folder_path, is_folder=True, create=create) 424 | 425 | def get_file(self, file_path, is_folder=False, create=False): 426 | 427 | if is_folder is True and file_path.endswith('/'): 428 | file_path = file_path[:-1] 429 | 430 | folders = file_path.split('/') 431 | 432 | file_name = None 433 | if is_folder is False: 434 | file_name = folders.pop() 435 | 436 | parent = 'root' 437 | 438 | for cur_folder in folders: 439 | escaped_folder = cur_folder.replace("'", "\\'") 440 | query = ("'{}' in parents and trashed=false and " 441 | "mimeType='application/vnd.google-apps.folder' and " 442 | "title='{}'".format(parent, escaped_folder)) 443 | file_list = (self.__service__.files() 444 | .list(q=query).execute()['items']) 445 | if len(file_list) > 1: 446 | raise RuntimeError('Multiple folders with name "{}" exist' 447 | .format(cur_folder)) 448 | elif len(file_list) is 0: 449 | if create is False: 450 | raise ItemDoesNotExistError('Folder "{}" does not exist' 451 | .format(cur_folder)) 452 | parent = self.create_folder_helper(cur_folder, parent)['id'] 453 | if parent is None: 454 | raise RuntimeError('Unable to create folder "{}"' 455 | .format(cur_folder)) 456 | else: 457 | parent = file_list[0]['id'] 458 | 459 | if is_folder is True: 460 | return parent 461 | 462 | escaped_file_name = file_name.replace("'", "\\'") 463 | query = ("'{}' in parents and trashed=false and title='{}'" 464 | .format(parent, escaped_file_name)) 465 | file_list = self.__service__.files().list(q=query).execute()['items'] 466 | if len(file_list) > 1: 467 | raise RuntimeError('Multiple files with name "{}" exist' 468 | .format(file_name)) 469 | elif len(file_list) is 0: 470 | raise ItemDoesNotExistError('File "{}" does not exist' 471 | .format(file_name)) 472 | 473 | return file_list[0] 474 | 475 | def create_folder(self, folder_path): 476 | self.get_folder(folder_path, create=True) 477 | 478 | def create_folder_helper(self, folder_name, parent, modified_time=None): 479 | 480 | mime_type = 'application/vnd.google-apps.folder' 481 | parents = [] 482 | if parent is not None: 483 | parents.append({"id": parent}) 484 | body = { 485 | 'title': folder_name, 486 | 'mimeType': mime_type, 487 | 'parents': parents, 488 | } 489 | if modified_time is not None: 490 | body['modifiedDate'] = modified_time 491 | 492 | try: 493 | file = (self.__service__.files().insert(body=body) 494 | .execute()) 495 | print("Folder creation complete") 496 | return file 497 | except apiclient.errors.HttpError as error: 498 | print('An error occured creating folder: %s' % error) 499 | return None 500 | 501 | def get_file_name(self, file): 502 | return file['title'] 503 | 504 | def is_folder_from_file_type(self, file): 505 | return file['mimeType'] == 'application/vnd.google-apps.folder' 506 | 507 | # Formatting code from http://stackoverflow.com/questions/1094841/ 508 | def format_bytes(self, num, suffix='B'): 509 | for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: 510 | if abs(num) < 1024.0: 511 | return "%3.2f%s%s" % (num, unit, suffix) 512 | num /= 1024.0 513 | return "%.2f%s%s" % (num, 'Yi', suffix) 514 | 515 | def get_quota(self): 516 | about = self.__service__.about().get().execute() 517 | 518 | quota_type = about['quotaType'] 519 | if quota_type == 'UNLIMITED': 520 | 521 | result = "Total quota: Unlimited\n" 522 | result += "Used quota: {}\n" 523 | result += "Data in Trash: {}" 524 | used_quota = int(about['quotaBytesUsedAggregate']) 525 | trashed_quota = int(about['quotaBytesUsedInTrash']) 526 | result = (result. 527 | format(self.format_bytes(used_quota), 528 | self.format_bytes(trashed_quota))) 529 | else: 530 | total_quota = int(about['quotaBytesTotal']) 531 | used_quota = int(about['quotaBytesUsedAggregate']) 532 | remaining_quota = total_quota-used_quota 533 | trashed_quota = int(about['quotaBytesUsedInTrash']) 534 | percentage = float(used_quota)/total_quota*100 535 | result = (("Total quota: {}\n" 536 | "Used quota: {}\n" 537 | "Remaining Quota: {}\n" 538 | "Data in Trash: {}\n" 539 | "Percentage Used {}%") 540 | .format(self.format_bytes(total_quota), 541 | self.format_bytes(used_quota), 542 | self.format_bytes(remaining_quota), 543 | self.format_bytes(trashed_quota), 544 | float("{0:.2f}".format(percentage)))) 545 | return result 546 | -------------------------------------------------------------------------------- /clouddrivestorageservice.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Darryl Tam 2 | 3 | # This file is part of MultiDrive. 4 | 5 | # MultiDrive is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | 10 | # MultiDrive is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | 15 | # You should have received a copy of the GNU General Public License 16 | # along with MultiDrive. If not, see . 17 | 18 | 19 | import requests 20 | import json 21 | from dateutil.parser import parse 22 | import datetime 23 | import urllib.parse 24 | import os 25 | 26 | import logging 27 | from mimetypes import guess_type 28 | 29 | from requests_toolbelt import MultipartEncoder 30 | import time 31 | 32 | from storageservice import StorageService 33 | from enum import Enum 34 | import hashlib 35 | 36 | 37 | class ItemDoesNotExistError(RuntimeError): 38 | pass 39 | 40 | 41 | class WrongTypeError(RuntimeError): 42 | pass 43 | 44 | 45 | class RemoteConnectionError(RuntimeError): 46 | pass 47 | 48 | 49 | class RequestType(Enum): 50 | GET = 0 51 | PUT = 1 52 | POST = 2 53 | 54 | 55 | class HashFile(object): 56 | def set_file(self, cur_file): 57 | self.file = cur_file 58 | self.cur_file_hash = hashlib.md5() 59 | self.calculate_len() 60 | 61 | def calculate_len(self): 62 | pos = self.file.tell() 63 | self.file.seek(0, os.SEEK_END) 64 | self.len = self.file.tell()-pos 65 | self.file.seek(pos, os.SEEK_SET) 66 | 67 | def read(self, *args): 68 | chunk = self.file.read(*args) 69 | if len(chunk) > 0: 70 | self.cur_file_hash.update(chunk) 71 | self.calculate_len() 72 | return chunk 73 | 74 | def get_md5(self): 75 | return self.cur_file_hash.hexdigest() 76 | 77 | 78 | class UTC(datetime.tzinfo): 79 | """UTC""" 80 | 81 | def utcoffset(self, dt): 82 | return datetime.timedelta(0) 83 | 84 | def tzname(self, dt): 85 | return "UTC" 86 | 87 | def dst(self, dt): 88 | return datetime.timedelta(0) 89 | 90 | 91 | class CloudDriveStorageService(StorageService): 92 | 93 | cloud_drive_url_root = "https://drive.amazonaws.com" 94 | cloud_drive_end_point = None 95 | content_url = None 96 | metadata_url = None 97 | root_folder = None 98 | 99 | def authorize(self): 100 | logger = logging.getLogger("multidrive") 101 | logger.debug("Authorize Cloud Drive Storage Service") 102 | 103 | with open('cloud_drive_client_secrets.json', 'r') as f: 104 | config = json.load(f) 105 | self.__client_id__ = config['client_id'] 106 | self.__client_secret__ = config['client_secret'] 107 | self.__return_uri__ = config['return_uri'] 108 | # If there's an error loading file, tell the user, as ask for client_id 109 | # and secret 110 | 111 | self.load_tokens() 112 | self.load_end_points() 113 | self.load_root_folder() 114 | 115 | def http_request(self, url, request_type, status_codes=(), headers={}, 116 | stream=False, data="", params=None, 117 | severe_status_codes=(), 118 | use_access_token=False, action_string="OneDrive HTTP", 119 | max_tries=6, 120 | use_multipart_encoder=False, 121 | multipart_encoder_fields=None, 122 | multipart_encoder_content=None, 123 | multipart_hash_file=None): 124 | logger = logging.getLogger("multidrive") 125 | 126 | if use_access_token is True: 127 | headers['Authorization'] = "Bearer " + self.get_access_token() 128 | 129 | if use_multipart_encoder is True: 130 | cur_multipart_file = open(multipart_encoder_content[1], 'rb') 131 | multipart_hash_file.set_file(cur_multipart_file) 132 | cur_multipart_content = ('content', (multipart_encoder_content[0], 133 | multipart_hash_file, 134 | multipart_encoder_content[2])) 135 | multipart_encoder_fields.append(cur_multipart_content) 136 | data = MultipartEncoder(fields=multipart_encoder_fields) 137 | headers["Content-Type"] = data.content_type 138 | 139 | try: 140 | if request_type == RequestType.GET: 141 | response = requests.get(url, headers=headers, params=params, 142 | stream=stream) 143 | elif request_type == RequestType.PUT: 144 | response = requests.put(url, headers=headers, data=data, 145 | params=params) 146 | elif request_type == RequestType.POST: 147 | response = requests.post(url, headers=headers, data=data) 148 | if use_multipart_encoder is True: 149 | logger.info("Current hash: "+multipart_hash_file.get_md5()) 150 | except requests.exceptions.ConnectionError as err: 151 | logger.warning("ConnectionError: {}".format(err)) 152 | response = None 153 | finally: 154 | if use_multipart_encoder is True: 155 | cur_multipart_file.close() 156 | 157 | tries = 0 158 | while response is None or (response.status_code not in status_codes 159 | and tries < max_tries): 160 | tries += 1 161 | logger.warning("Retry " + str(tries)) 162 | sleep_length = float(1 << tries) / 2 163 | 164 | if response is not None: 165 | logger.warning("{}: Connection failed Code: {}" 166 | .format(action_string, 167 | str(response.status_code))) 168 | logger.warning("Error: {}".format(response.text)) 169 | logger.warning("Headers: {}".format(str(response.headers))) 170 | 171 | if 'Retry-After' in response.headers: 172 | logger.warning("Server requested wait of {} seconds". 173 | format(response.headers['Retry-After'])) 174 | sleep_length = int(response.headers['Retry-After']) 175 | elif response.status_code in severe_status_codes: 176 | logger.warning("Server Error, increasing wait time") 177 | sleep_length *= 20 178 | 179 | logger.warning("Waiting {} second(s) for next attempt" 180 | .format(str(sleep_length))) 181 | 182 | time.sleep(sleep_length) 183 | # Force refresh of token once in case it's expired 184 | if (tries == 1): 185 | self.refresh_access_token() 186 | 187 | if use_access_token is True: 188 | headers['Authorization'] = "Bearer " + self.get_access_token() 189 | 190 | if use_multipart_encoder is True: 191 | cur_multipart_file = open(multipart_encoder_content[1], 'rb') 192 | multipart_hash_file.set_file(cur_multipart_file) 193 | cur_multipart_content = ('content', 194 | (multipart_encoder_content[0], 195 | multipart_hash_file, 196 | multipart_encoder_content[2])) 197 | multipart_encoder_fields.append(cur_multipart_content) 198 | data = MultipartEncoder(fields=multipart_encoder_fields) 199 | 200 | try: 201 | if request_type == RequestType.GET: 202 | response = requests.get(url, headers=headers, 203 | params=params, stream=stream) 204 | elif request_type == RequestType.PUT: 205 | response = requests.put(url, headers=headers, data=data, 206 | params=params) 207 | elif request_type == RequestType.POST: 208 | response = requests.post(url, headers=headers, data=data) 209 | except requests.exceptions.ConnectionError as err: 210 | logger.warning("ConnectionError: {}".format(err)) 211 | response = None 212 | finally: 213 | if use_multipart_encoder is True: 214 | cur_multipart_file.close() 215 | 216 | if response is None: 217 | raise RemoteConnectionError("{}: Unable to complete request." 218 | .format(action_string)) 219 | if response.status_code not in status_codes: 220 | logger.warning("{}: Connection failed Code: {}" 221 | .format(action_string, str(response.status_code))) 222 | logger.warning("Error: {}".format(response.text)) 223 | logger.warning("Headers: {}".format(str(response.headers))) 224 | logger.warning("Retry " + str(tries)) 225 | raise RemoteConnectionError("{}: Unable to complete request." 226 | .format(action_string)) 227 | 228 | return response 229 | 230 | def get_tokens_from_code(self, code): 231 | data = {'client_id': self.__client_id__, 232 | 'redirect_uri': self.__return_uri__, 233 | 'client_secret': self.__client_secret__, 234 | 'code': code, 235 | 'grant_type': 'authorization_code'} 236 | headers = {'Content-Type': 'application/x-www-form-urlencoded'} 237 | url = 'https://api.amazon.com/auth/o2/token' 238 | response = self.http_request(url=url, 239 | request_type=RequestType.POST, 240 | status_codes=(requests.codes.ok,), 241 | headers=headers, 242 | data=data, use_access_token=False, 243 | action_string="Cloud Drive Get Tokens " 244 | "From Code") 245 | data = json.loads(response.text) 246 | return (data['refresh_token'], 247 | data['access_token'], 248 | int(data['expires_in'])) 249 | 250 | def load_tokens(self): 251 | refresh_token = None 252 | try: 253 | with open('cloud_drive_settings.json', 'r') as f: 254 | config = json.load(f) 255 | refresh_token = config['refresh_token'] 256 | except IOError: 257 | pass 258 | 259 | if refresh_token is not None: 260 | self.__refresh_token__ = refresh_token 261 | self.refresh_access_token() 262 | return 263 | 264 | parameters = {'client_id': self.__client_id__, 265 | 'scope': 'clouddrive:read clouddrive:write', 266 | 'response_type': 'code', 267 | 'redirect_uri': self.__return_uri__} 268 | print(("Go to this URL to authorize. Input the redirected URL: " 269 | "https://www.amazon.com/ap/oa?") 270 | + urllib.parse.urlencode(parameters)) 271 | 272 | response = input("Enter the URL you were redirected to: ") 273 | code = urllib.parse.parse_qs( 274 | urllib.parse.urlparse(response).query)['code'][0] 275 | 276 | (refresh_token, access_token, expiry) = self.get_tokens_from_code(code) 277 | 278 | if (refresh_token is None): 279 | raise RuntimeError("Unable to get refresh token") 280 | 281 | config = {'refresh_token': refresh_token} 282 | with open('cloud_drive_settings.json', 'w') as f: 283 | json.dump(config, f) 284 | 285 | self.__refresh_token__ = refresh_token 286 | self.set_access_token(access_token, expiry) 287 | return 288 | 289 | def get_access_token(self): 290 | now = datetime.datetime.utcnow() 291 | if (now > self.__token__expiry__): 292 | self.refresh_access_token() 293 | return self.__access_token__ 294 | 295 | def set_access_token(self, access_token, expiry): 296 | self.__access_token__ = access_token 297 | self.__token__expiry__ = (datetime.datetime.utcnow() + 298 | datetime.timedelta(seconds=(expiry-60))) 299 | 300 | def refresh_access_token(self): 301 | data = {'client_id': self.__client_id__, 302 | 'redirect_uri': self.__return_uri__, 303 | 'client_secret': self.__client_secret__, 304 | 'refresh_token': self.__refresh_token__, 305 | 'grant_type': 'refresh_token'} 306 | headers = {'Content-Type': 'application/x-www-form-urlencoded'} 307 | url = 'https://api.amazon.com/auth/o2/token' 308 | response = self.http_request(url=url, 309 | request_type=RequestType.POST, 310 | status_codes=(requests.codes.ok,), 311 | headers=headers, 312 | data=data, 313 | use_access_token=False, 314 | action_string="Cloud Drive Refresh Access" 315 | " Token") 316 | 317 | data = json.loads(response.text) 318 | self.set_access_token(data['access_token'], int(data['expires_in'])) 319 | return 320 | 321 | def load_end_points(self): 322 | url = self.cloud_drive_url_root + '/drive/v1/account/endpoint' 323 | response = self.http_request(url=url, 324 | request_type=RequestType.GET, 325 | status_codes=(requests.codes.ok,), 326 | use_access_token=True, 327 | action_string="Cloud Drive End Points") 328 | data = json.loads(response.text) 329 | if data['customerExists'] is not True: 330 | raise RuntimeError("Error with account") 331 | self.content_url = data['contentUrl'] 332 | self.metadata_url = data['metadataUrl'] 333 | 334 | def load_root_folder(self): 335 | url = self.metadata_url + '/nodes?filters=isRoot:true' 336 | response = self.http_request(url=url, 337 | request_type=RequestType.GET, 338 | status_codes=(requests.codes.ok,), 339 | use_access_token=True, 340 | action_string="Cloud Drive Root Folder") 341 | 342 | data = json.loads(response.text) 343 | if 'data' not in data: 344 | raise RuntimeError("Error getting root folder") 345 | self.root_folder = data['data'][0]['id'] 346 | 347 | def upload(self, file_path, destination=None, 348 | modified_time=None, create_folder=False, overwrite=False): 349 | logger = logging.getLogger("multidrive") 350 | logger.debug("Upload {} Cloud Drive Storage Service".format(file_path)) 351 | 352 | destination_id = self.root_folder 353 | if destination is not None and destination != "": 354 | destination_id = self.get_folder(self.root_folder, 355 | destination, 356 | create_folder) 357 | 358 | file_name = os.path.basename(file_path) 359 | cur_file = self.get_file(destination_id, file_name) 360 | cur_hash_file = HashFile() 361 | 362 | NUM_ATTEMPTS = 5 363 | cur_attempt = 1 364 | while cur_attempt <= NUM_ATTEMPTS: 365 | 366 | if cur_file is None: 367 | url = self.content_url + "/nodes?suppress=deduplication" 368 | 369 | metadata = {} 370 | metadata['name'] = file_name 371 | metadata['kind'] = "FILE" 372 | metadata['parents'] = [destination_id] 373 | 374 | mime_type = guess_type(file_path)[0] 375 | if not mime_type: 376 | mime_type = 'application/octet-stream' 377 | 378 | fields = [('metadata', ("", json.dumps(metadata)))] 379 | content = (file_name, file_path, mime_type) 380 | 381 | response = self.http_request(url=url, 382 | request_type=RequestType.POST, 383 | status_codes=(requests.codes. 384 | created,), 385 | use_access_token=True, 386 | action_string="Upload File", 387 | max_tries=10, 388 | use_multipart_encoder=True, 389 | multipart_encoder_fields=fields, 390 | multipart_encoder_content=content, 391 | multipart_hash_file=cur_hash_file) 392 | else: 393 | if overwrite is False: 394 | raise RuntimeError("File: {} exists, but " 395 | "overwrite is not set" 396 | .format(file_name)) 397 | url = self.content_url + "/nodes/"+cur_file['id']+"/content" 398 | 399 | mime_type = guess_type(file_path)[0] 400 | if not mime_type: 401 | mime_type = 'application/octet-stream' 402 | 403 | content = (file_name, file_path, mime_type) 404 | cur_hash_file = HashFile() 405 | response = self.http_request(url=url, 406 | request_type=RequestType.PUT, 407 | status_codes=(requests.codes.ok,), 408 | use_access_token=True, 409 | action_string="Upload File " 410 | "Overwrite", 411 | max_tries=10, 412 | use_multipart_encoder=True, 413 | multipart_encoder_fields=[], 414 | multipart_encoder_content=content, 415 | multipart_hash_file=cur_hash_file) 416 | 417 | server_hash = json.loads(response.text)['contentProperties']['md5'] 418 | 419 | cur_attempt += 1 420 | if (cur_hash_file.get_md5() == server_hash.lower()): 421 | break 422 | logger.warning("Hash of uploaded file does " 423 | "not match server. Attempting again") 424 | 425 | if (cur_hash_file.get_md5() != server_hash.lower()): 426 | raise RuntimeError("Hash of uploaded file does " 427 | "not match server.") 428 | 429 | print("{} successfully uploaded".format(file_name)) 430 | 431 | def get_folder(self, cur_folder, folder_path, create=False): 432 | if folder_path.endswith('/'): 433 | folder_path = folder_path[:-1] 434 | 435 | split_path = folder_path.split('/') 436 | # cur_path = cur_folder 437 | # print "Path: "+ str(split_path) 438 | create_rest = False 439 | while len(split_path) > 0: 440 | cur_item = split_path.pop(0) 441 | data = None 442 | if create_rest is False: 443 | params = urllib.parse.urlencode({'filters': 'name:' 444 | + cur_item.replace(" ", "\ ")}) 445 | url = self.metadata_url + '/nodes/' + cur_folder + '/children' 446 | response = self.http_request(url=url, 447 | request_type=RequestType.GET, 448 | status_codes=(requests.codes.ok, 449 | requests.codes. 450 | bad_request), 451 | use_access_token=True, 452 | params=params, 453 | action_string='Get Folder') 454 | if response.status_code == requests.codes.bad_request: 455 | raise ItemDoesNotExistError("Error: Folder {} does not " 456 | "exist.".format(cur_item)) 457 | 458 | data = json.loads(response.text) 459 | if 'data' not in data: 460 | raise RuntimeError("Error getting folder " + cur_item) 461 | 462 | if create_rest is True or len(data['data']) == 0: 463 | if create is False: 464 | raise ItemDoesNotExistError("Error: Folder {} does not " 465 | "exist and createfolder is " 466 | "not set.".format(cur_item)) 467 | create_rest = True 468 | url = self.metadata_url + "/nodes" 469 | 470 | metadata = {} 471 | metadata['name'] = cur_item 472 | metadata['kind'] = "FOLDER" 473 | metadata['parents'] = [cur_folder] 474 | 475 | data = json.dumps(metadata) 476 | 477 | response = self.http_request(url=url, 478 | request_type=RequestType.POST, 479 | status_codes=(requests.codes. 480 | created,), 481 | use_access_token=True, 482 | data=data, 483 | action_string='Create Folder') 484 | 485 | data = json.loads(response.text) 486 | cur_folder = data['id'] 487 | elif len(data['data']) > 1: 488 | raise RuntimeError("Error: Multiple items with name: " + 489 | cur_item) 490 | else: 491 | if data['data'][0]['kind'] != "FOLDER": 492 | raise WrongTypeError("Error: {} is not a folder." 493 | .format(cur_item)) 494 | cur_folder = data['data'][0]['id'] 495 | 496 | return cur_folder 497 | 498 | def get_file(self, folder_id, file_name): 499 | params = urllib.parse.urlencode({'filters': 'name:' + 500 | file_name.replace(" ", "\ ")}) 501 | 502 | url = self.metadata_url + '/nodes/' + folder_id + '/children' 503 | response = self.http_request(url=url, 504 | request_type=RequestType.GET, 505 | status_codes=(requests.codes.ok,), 506 | use_access_token=True, 507 | params=params, 508 | action_string='Get File') 509 | 510 | data = json.loads(response.text) 511 | if 'data' not in data: 512 | raise RuntimeError("Error getting file " + file_name) 513 | if (len(data['data']) == 0): 514 | return None 515 | elif len(data['data']) > 1: 516 | raise RuntimeError("Error: Multiple items with name: " + 517 | file_name) 518 | 519 | if data['data'][0]['kind'] != "FILE": 520 | raise RuntimeError("Error: {} exists, but is not a file." 521 | .format(file_name)) 522 | 523 | return data['data'][0] 524 | 525 | def download(self, file_path, destination=None, overwrite=False): 526 | print("Download {} Cloud Drive Storage Service".format(file_path)) 527 | (folder, file_name) = os.path.split(file_path) 528 | 529 | if folder is None or folder == "": 530 | folder = self.root_folder 531 | else: 532 | folder = self.get_folder(self.root_folder, folder, create=False) 533 | 534 | cur_file = self.get_file(folder, file_name) 535 | 536 | if cur_file is None: 537 | raise RuntimeError("File {} does not exist".format(file_path)) 538 | return self.download_item(cur_file, destination, overwrite=overwrite, 539 | create_folder=False) 540 | 541 | def download_item(self, cur_file, destination=None, overwrite=False, 542 | create_folder=False): 543 | logger = logging.getLogger("multidrive") 544 | local_path = cur_file['name'] 545 | 546 | if destination is not None: 547 | local_path = os.path.join(destination, local_path) 548 | 549 | if cur_file['kind'] == 'FOLDER': 550 | if create_folder is False: 551 | raise RuntimeError("Error: Folder chosen to be downloaded.") 552 | if not os.path.exists(local_path): 553 | # Add proper error message here? 554 | os.mkdir(local_path) 555 | return (local_path, cur_file['modifiedDate']) 556 | if os.path.isdir(local_path): 557 | raise RuntimeError("Local destination is a folder") 558 | if overwrite is False and os.path.isfile(local_path): 559 | raise RuntimeError("Local file {} exists. Enable overwrite " 560 | "option to continue.".format(local_path)) 561 | 562 | remote_hash = cur_file['contentProperties']['md5'].lower() 563 | NUM_ATTEMPTS = 5 564 | cur_attempt = 1 565 | while cur_attempt <= NUM_ATTEMPTS: 566 | f = open(local_path, "wb") 567 | 568 | url = self.content_url+"/nodes/"+cur_file['id']+"/content" 569 | logger.info("URL to save file is: "+url) 570 | 571 | response = self.http_request(url=url, 572 | request_type=RequestType.GET, 573 | status_codes=(requests.codes.ok,), 574 | use_access_token=True, 575 | stream=True, 576 | action_string='Download Item') 577 | 578 | size = 0 579 | cur_file_hash = hashlib.md5() 580 | for chunk in response.iter_content(chunk_size=4*1024*1024): 581 | if chunk: # filter out keep-alive new chunks 582 | cur_file_hash.update(chunk) 583 | f.write(chunk) 584 | f.flush() 585 | size += 1 586 | if size % 100 == 0: 587 | logger.info(str(size*4) + "MB written") 588 | os.fsync(f.fileno()) 589 | f.close() 590 | 591 | cur_attempt += 1 592 | if (remote_hash == (cur_file_hash.hexdigest())): 593 | break 594 | logger.warning("Hash of downloaded file does " 595 | "not match server. Attempting again") 596 | 597 | if (remote_hash != (cur_file_hash.hexdigest())): 598 | raise RuntimeError("Hash of downloaded file does " 599 | "not match server.") 600 | 601 | lastModifiedDateTimeString = cur_file['modifiedDate'] 602 | modifiedDate = parse(lastModifiedDateTimeString) 603 | 604 | os.utime(local_path, (time.mktime(modifiedDate.timetuple()), 605 | time.mktime(modifiedDate.timetuple()))) 606 | 607 | print(local_path + " has been saved to disk") 608 | 609 | # TODO: deal with return values. 610 | return (local_path, lastModifiedDateTimeString) 611 | 612 | def create_folder(self, folder_path): 613 | self.get_folder(self.root_folder, folder_path, create=True) 614 | 615 | def is_folder(self, folder_path): 616 | if folder_path is None or len(folder_path) == 0 or folder_path == "/": 617 | return True 618 | try: 619 | result = self.get_folder(self.root_folder, 620 | folder_path, 621 | create=False) 622 | if result is None: 623 | return False 624 | return True 625 | except (ItemDoesNotExistError, WrongTypeError): 626 | return False 627 | 628 | def list_folder(self, folder_path): 629 | base_folder = self.root_folder 630 | if (folder_path is not None and (len(folder_path) > 0 and 631 | folder_path != "/")): 632 | base_folder = self.get_folder(base_folder, 633 | folder_path, 634 | create=False) 635 | print("Getting listing for {}".format(folder_path)) 636 | folder_list = self.get_folder_listing(base_folder, []) 637 | return folder_list 638 | 639 | def get_folder_listing(self, cur_folder, path_list): 640 | logger = logging.getLogger("multidrive") 641 | result_list = [] 642 | 643 | url = self.metadata_url + '/nodes/' + cur_folder + '/children' 644 | params = {} 645 | data = [] 646 | num_files = 0 647 | while True: 648 | response = self.http_request(url=url, 649 | request_type=RequestType.GET, 650 | status_codes=(requests.codes.ok, 651 | requests.codes. 652 | not_found), 653 | use_access_token=True, 654 | params=params, 655 | action_string='Get Folder Listing') 656 | 657 | if response.status_code == requests.codes.not_found: 658 | logger.warning("Item not found: " + cur_folder) 659 | raise RuntimeError("Item not found. Possible bad path: " 660 | + cur_folder) 661 | 662 | cur_response = json.loads(response.text) 663 | if 'data' not in cur_response: 664 | raise RuntimeError("Error getting folder " + cur_folder) 665 | data.extend(cur_response['data']) 666 | num_files += len(cur_response['data']) 667 | if num_files >= cur_response['count']: 668 | break 669 | params['startToken'] = cur_response['nextToken'] 670 | 671 | data.sort(key=lambda cur_file: cur_file['name']) 672 | 673 | for current_item in data: 674 | result_list.append((current_item, path_list)) 675 | if current_item['kind'] == "FOLDER": 676 | new_list = list(path_list) 677 | new_list.append(current_item['name']) 678 | result_list.extend(self.get_folder_listing( 679 | current_item['id'], new_list)) 680 | 681 | return result_list 682 | 683 | def get_file_name(self, file): 684 | return file['name'] 685 | 686 | def is_folder_from_file_type(self, file): 687 | return file['kind'] == "FOLDER" 688 | 689 | # Formatting code from http://stackoverflow.com/questions/1094841/ 690 | def format_bytes(self, num, suffix='B'): 691 | for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: 692 | if abs(num) < 1024.0: 693 | return "%3.2f%s%s" % (num, unit, suffix) 694 | num /= 1024.0 695 | return "%.2f%s%s" % (num, 'Yi', suffix) 696 | 697 | def get_quota(self): 698 | 699 | url = self.metadata_url + '/account/quota' 700 | status_codes = (requests.codes.ok,) 701 | 702 | response = self.http_request(url=url, 703 | request_type=RequestType.GET, 704 | status_codes=status_codes, 705 | use_access_token=True, 706 | action_string="Get Cloud Drive Quota", 707 | max_tries=8) 708 | quota_data = json.loads(response.text) 709 | 710 | url = self.metadata_url + '/account/usage' 711 | response = self.http_request(url=url, 712 | request_type=RequestType.GET, 713 | status_codes=status_codes, 714 | use_access_token=True, 715 | action_string="Get Cloud Drive Quota", 716 | max_tries=8) 717 | usage_data = json.loads(response.text) 718 | 719 | other_usage = usage_data['other']['total']['bytes'] 720 | doc_usage = usage_data['doc']['total']['bytes'] 721 | photo_usage = usage_data['photo']['total']['bytes'] 722 | video_usage = usage_data['video']['total']['bytes'] 723 | total_usage = other_usage + doc_usage + photo_usage + video_usage 724 | 725 | usage_result = "Documents Usage: "+self.format_bytes(doc_usage)+"\n" 726 | usage_result += "Photo Usage: "+self.format_bytes(photo_usage)+"\n" 727 | usage_result += "Video Usage "+self.format_bytes(video_usage)+"\n" 728 | usage_result += "Other Usage: "+self.format_bytes(other_usage)+"\n" 729 | usage_result += "Total Usage: "+self.format_bytes(total_usage) 730 | 731 | if ('plans' in quota_data and 'CDSPUS0000' in quota_data['plans']): 732 | result = ("Total Quota: Unlimited\n") 733 | result += usage_result 734 | else: 735 | total_quota = quota_data['quota'] 736 | remaining_quota = quota_data['available'] 737 | used_quota = total_quota-remaining_quota 738 | percentage = float(used_quota)/total_quota*100 739 | result = (("Total quota: {}\n" 740 | "Used quota: {}\n" 741 | "Remaining Quota: {}\n" 742 | "Percentage Quota Used {}%\n") 743 | .format(self.format_bytes(total_quota), 744 | self.format_bytes(used_quota), 745 | self.format_bytes(remaining_quota), 746 | float("{0:.2f}". 747 | format(percentage)))) 748 | result += usage_result 749 | return result 750 | -------------------------------------------------------------------------------- /onedrivestorageservice.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2015 Darryl Tam 2 | 3 | # This file is part of MultiDrive. 4 | 5 | # MultiDrive is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | 10 | # MultiDrive is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | 15 | # You should have received a copy of the GNU General Public License 16 | # along with MultiDrive. If not, see . 17 | 18 | 19 | import requests 20 | import json 21 | from dateutil.parser import parse 22 | import datetime 23 | import urllib.parse 24 | from urllib.parse import urlparse, parse_qs 25 | import os 26 | from enum import Enum 27 | import hashlib 28 | import logging 29 | 30 | import time 31 | 32 | from storageservice import StorageService 33 | 34 | 35 | class ItemDoesNotExistError(RuntimeError): 36 | pass 37 | 38 | 39 | class RemoteConnectionError(RuntimeError): 40 | pass 41 | 42 | 43 | class UTC(datetime.tzinfo): 44 | """UTC""" 45 | 46 | def utcoffset(self, dt): 47 | return datetime.timedelta(0) 48 | 49 | def tzname(self, dt): 50 | return "UTC" 51 | 52 | def dst(self, dt): 53 | return datetime.timedelta(0) 54 | 55 | 56 | class RequestType(Enum): 57 | GET = 0 58 | PUT = 1 59 | POST = 2 60 | 61 | 62 | class OneDriveStorageService(StorageService): 63 | 64 | onedrive_url_root = "https://api.onedrive.com/v1.0" 65 | 66 | def authorize(self): 67 | self.__app_folder__ = False 68 | logger = logging.getLogger("multidrive") 69 | logger.debug("Authorize OneDrive Storage Service") 70 | 71 | with open('onedrive_client_secrets.json', 'r') as f: 72 | config = json.load(f) 73 | self.__client_id__ = config['client_id'] 74 | self.__client_secret__ = config['client_secret'] 75 | # TODO: If there's an error loading file, tell the user, and 76 | # ask for client_id and secret 77 | 78 | self.load_tokens() 79 | 80 | def get_tokens_from_code(self, code): 81 | data = {'client_id': self.__client_id__, 82 | 'redirect_uri': 'https://login.live.com/oauth20_desktop.srf', 83 | 'client_secret': self.__client_secret__, 84 | 'code': code, 85 | 'grant_type': 'authorization_code'} 86 | headers = {'Content-Type': 'application/x-www-form-urlencoded'} 87 | url = 'https://login.live.com/oauth20_token.srf' 88 | response = self.http_request(url=url, 89 | request_type=RequestType.POST, 90 | status_codes=(requests.codes.ok,), 91 | headers=headers, 92 | data=data, 93 | use_access_token=False, 94 | action_string="OneDrive Get Tokens " 95 | "From Code") 96 | data = json.loads(response.text) 97 | return (data['refresh_token'], 98 | data['access_token'], 99 | int(data['expires_in'])) 100 | 101 | def http_request(self, url, request_type, status_codes=(), headers={}, 102 | stream=False, data="", params=None, 103 | severe_status_codes=(), 104 | use_access_token=False, action_string="OneDrive HTTP", 105 | max_tries=6, timeout=120): 106 | logger = logging.getLogger("multidrive") 107 | 108 | if use_access_token is True: 109 | headers['Authorization'] = "Bearer " + self.get_access_token() 110 | 111 | try: 112 | if request_type == RequestType.GET: 113 | response = requests.get(url, headers=headers, params=params, 114 | stream=stream, timeout=timeout) 115 | elif request_type == RequestType.PUT: 116 | response = requests.put(url, headers=headers, data=data, 117 | params=params, timeout=timeout) 118 | elif request_type == RequestType.POST: 119 | response = requests.post(url, headers=headers, data=data, 120 | timeout=timeout) 121 | except requests.exceptions.ConnectionError as err: 122 | logger.warning("ConnectionError: {}".format(err)) 123 | response = None 124 | except requests.exceptions.Timeout as err: 125 | logger.warning("Timeout: {}".format(err)) 126 | response = None 127 | 128 | tries = 0 129 | while response is None or (response.status_code not in status_codes 130 | and tries < max_tries): 131 | tries += 1 132 | logger.warning("Retry " + str(tries)) 133 | sleep_length = float(1 << tries) / 2 134 | if response is not None: 135 | logger.warning("{}: Connection failed Code: {}" 136 | .format(action_string, 137 | str(response.status_code))) 138 | logger.warning("Error: {}".format(response.text)) 139 | logger.warning("Headers: {}".format(str(response.headers))) 140 | 141 | if 'Retry-After' in response.headers: 142 | logger.warning("Server requested wait of {} seconds". 143 | format(response.headers['Retry-After'])) 144 | sleep_length = int(response.headers['Retry-After']) 145 | elif response.status_code in severe_status_codes: 146 | logger.warning("Server Error, increasing wait time") 147 | sleep_length *= 20 148 | 149 | logger.warning("Waiting {} second(s) for next attempt" 150 | .format(str(sleep_length))) 151 | 152 | time.sleep(sleep_length) 153 | # Force refresh of token once in case it's expired 154 | if (tries == 1): 155 | self.refresh_access_token() 156 | 157 | if use_access_token is True: 158 | headers['Authorization'] = "Bearer " + self.get_access_token() 159 | 160 | try: 161 | if request_type == RequestType.GET: 162 | response = requests.get(url, headers=headers, 163 | params=params, stream=stream, 164 | timeout=timeout) 165 | elif request_type == RequestType.PUT: 166 | response = requests.put(url, headers=headers, data=data, 167 | params=params, timeout=timeout) 168 | elif request_type == RequestType.POST: 169 | response = requests.post(url, headers=headers, data=data, 170 | timeout=timeout) 171 | except requests.exceptions.ConnectionError as err: 172 | logger.warning("ConnectionError: {}".format(err)) 173 | response = None 174 | except requests.exceptions.Timeout as err: 175 | logger.warning("Timeout: {}".format(err)) 176 | response = None 177 | 178 | if response is None: 179 | logger.warning("Connection failed.") 180 | raise RemoteConnectionError("Unable to complete request.") 181 | 182 | if response.status_code not in status_codes: 183 | logger.warning("{}: Connection failed Code: {}" 184 | .format(action_string, str(response.status_code))) 185 | logger.warning("Error: {}".format(response.text)) 186 | logger.warning("Headers: {}".format(str(response.headers))) 187 | logger.warning("Retry " + str(tries)) 188 | raise RemoteConnectionError("{}: Unable to complete request." 189 | .format(action_string)) 190 | 191 | return response 192 | 193 | def get_access_token(self): 194 | now = datetime.datetime.utcnow() 195 | if (now > self.__token__expiry__): 196 | self.refresh_access_token() 197 | return self.__access_token__ 198 | 199 | def refresh_access_token(self): 200 | data = {'client_id': self.__client_id__, 201 | 'redirect_uri': 'https://login.live.com/oauth20_desktop.srf', 202 | 'client_secret': self.__client_secret__, 203 | 'refresh_token': self.__refresh_token__, 204 | 'grant_type': 'refresh_token'} 205 | headers = {'Content-Type': 'application/x-www-form-urlencoded'} 206 | url = 'https://login.live.com/oauth20_token.srf' 207 | response = self.http_request(url=url, 208 | request_type=RequestType.POST, 209 | status_codes=(requests.codes.ok,), 210 | headers=headers, 211 | data=data, 212 | use_access_token=False, 213 | action_string="OneDrive Refresh Access" 214 | "Token") 215 | 216 | data = json.loads(response.text) 217 | self.set_access_token(data['access_token'], int(data['expires_in'])) 218 | return 219 | 220 | def set_access_token(self, access_token, expiry): 221 | self.__access_token__ = access_token 222 | self.__token__expiry__ = (datetime.datetime.utcnow() + 223 | datetime.timedelta(seconds=(expiry-60))) 224 | 225 | def load_tokens(self): 226 | # logger = logging.getLogger("multidrive") 227 | refresh_token = None 228 | try: 229 | with open('onedrive_settings.json', 'r') as f: 230 | config = json.load(f) 231 | refresh_token = config['refresh_token'] 232 | except IOError: 233 | pass 234 | 235 | if refresh_token is not None: 236 | self.__refresh_token__ = refresh_token 237 | self.refresh_access_token() 238 | return 239 | 240 | parameters = {'client_id': self.__client_id__, 241 | 'scope': 'wl.offline_access onedrive.readwrite', 242 | 'response_type': 'code', 243 | 'redirect_uri': 244 | 'https://login.live.com/oauth20_desktop.srf'} 245 | if self.__app_folder__: 246 | parameters['scope'] = 'wl.offline_access onedrive.appfolder' 247 | 248 | print("Go to this URL to authorize. Input the redirected URL: " 249 | "https://login.live.com/oauth20_authorize.srf?" + 250 | urllib.parse.urlencode(parameters)) 251 | 252 | response = input("Enter the URL you were redirected to: ") 253 | code = parse_qs(urlparse(response).query)['code'][0] 254 | (refresh_token, access_token, expiry) = self.get_tokens_from_code(code) 255 | 256 | if (refresh_token is None): 257 | raise RuntimeError("Unable to get refresh token") 258 | 259 | config = {'refresh_token': refresh_token} 260 | with open('onedrive_settings.json', 'w') as f: 261 | json.dump(config, f) 262 | self.__refresh_token__ = refresh_token 263 | self.set_access_token(access_token, expiry) 264 | return 265 | 266 | def upload(self, file_path, destination=None, modified_time=None, 267 | create_folder=False, overwrite=False): 268 | logger = logging.getLogger("multidrive") 269 | logger.info("Upload {} OneDrive Storage Service".format(file_path)) 270 | 271 | file_name = os.path.basename(file_path) 272 | full_remote_path = file_name 273 | if destination is not None: 274 | if self.is_folder(destination) is False: 275 | if create_folder is False: 276 | raise RuntimeError("Destination folder not valid") 277 | self.create_folder(destination) 278 | 279 | if destination.endswith('/') is False: 280 | destination = destination+"/" 281 | full_remote_path = destination+full_remote_path 282 | 283 | file_size = os.path.getsize(file_path) 284 | 285 | payload = {} 286 | payload["@name.conflictBehavior"] = "fail" 287 | if overwrite is True: 288 | payload["@name.conflictBehavior"] = "replace" 289 | 290 | # Special case for empty file 291 | if file_size == 0: 292 | url = (self.onedrive_url_root+"/drive/root:/" + 293 | urllib.parse.quote(full_remote_path)+":/content") 294 | if self.__app_folder__: 295 | url = (self.onedrive_url_root+"/drive/special/approot:/" + 296 | urllib.parse.quote(full_remote_path)+":/content") 297 | 298 | response = self.http_request(url=url, 299 | request_type=RequestType.PUT, 300 | status_codes=(requests.codes.ok, 301 | requests.codes.created, 302 | requests.codes.accepted, 303 | requests.codes. 304 | conflict), 305 | data="", 306 | params=payload, 307 | use_access_token=True, 308 | action_string="Upload") 309 | 310 | if response.status_code in (requests.codes.conflict,): 311 | raise RuntimeError("File already exists") 312 | logger.info("Upload complete") 313 | return 314 | 315 | NUM_ATTEMPTS = 5 316 | cur_attempt = 1 317 | while cur_attempt <= NUM_ATTEMPTS: 318 | headers = {'Content-Type': "application/json"} 319 | 320 | url = (self.onedrive_url_root+"/drive/root:/" + 321 | urllib.parse.quote(full_remote_path) + 322 | ":/upload.createSession") 323 | 324 | if self.__app_folder__: 325 | url = (self.onedrive_url_root+"/drive/special/approot:/" + 326 | urllib.parse.quote(full_remote_path) + 327 | ":/upload.createSession") 328 | 329 | response = self.http_request(url=url, 330 | request_type=RequestType.POST, 331 | status_codes=(requests.codes.ok,), 332 | headers=headers, 333 | data=json.dumps(payload), 334 | use_access_token=True, 335 | action_string="Upload", 336 | timeout=120) 337 | 338 | data = json.loads(response.text) 339 | 340 | url = data['uploadUrl'] 341 | 342 | CHUNK_SIZE = 10*1024*1024 343 | chunk_start = 0 344 | chunk_end = CHUNK_SIZE - 1 345 | if chunk_end+1 >= file_size: 346 | chunk_end = file_size - 1 347 | response = None 348 | 349 | # TODO: Deal with insufficient Storage error (507) 350 | # TODO: Deal with other 400/500 series errors 351 | 352 | cur_file_hash = hashlib.sha1() 353 | with open(file_path, "rb") as f: 354 | retry_chunk = False 355 | while chunk_start < file_size: 356 | if retry_chunk is False: 357 | chunk_data = f.read(CHUNK_SIZE) 358 | cur_file_hash.update(chunk_data) 359 | retry_chunk = False 360 | headers = {} 361 | headers['Content-Length'] = str(file_size) 362 | headers['Content-Range'] = ('bytes {}-{}/{}'. 363 | format(chunk_start, 364 | chunk_end, 365 | file_size)) 366 | status_codes = (requests.codes.ok, 367 | requests.codes.created, 368 | requests.codes.accepted, 369 | requests.codes.conflict, 370 | requests.codes.range_not_satisfiable) 371 | # TODO: Further testing on some errors 372 | # err_codes = (requests.codes.server_error,) 373 | response = self.http_request(url=url, 374 | request_type=RequestType.PUT, 375 | headers=headers, 376 | status_codes=status_codes, 377 | # severe_status_codes=err_codes, 378 | data=chunk_data, 379 | use_access_token=True, 380 | action_string="Upload Chunk", 381 | timeout=120) 382 | 383 | # TODO: Check for proper response based on 384 | # location in file uploading. 385 | 386 | if response.status_code in (requests.codes.conflict,): 387 | raise RuntimeError("File Already Exists") 388 | 389 | if response.status_code in (requests.codes. 390 | range_not_satisfiable,): 391 | logger.warning("Got error {}".format(response.text)) 392 | logger.warning("DEBUG: Getting upload status") 393 | logger.warning("Current Chunk Start: " + 394 | str(chunk_start)) 395 | upload_status = self.get_upload_status(url) 396 | logger.warning("Status: " + str(upload_status)) 397 | if 'nextExpectedRanges' in upload_status: 398 | new_start_range = int(upload_status 399 | ['nextExpectedRanges'] 400 | [0].split("-")[0]) 401 | valid_chunk = (new_start_range > chunk_start and 402 | new_start_range < chunk_end) 403 | if (valid_chunk): 404 | difference = new_start_range-chunk_start 405 | chunk_start = new_start_range 406 | chunk_data = chunk_data[difference:] 407 | retry_chunk = True 408 | logger.warning("Attempting to retry part of " 409 | "current chunk") 410 | logger.warning("new chunk start: " + 411 | str(chunk_start)) 412 | logger.warning("new chunk end: " + 413 | str(chunk_end)) 414 | continue 415 | break 416 | 417 | print("{} of {} bytes sent, {}% complete" 418 | .format(str(chunk_end+1), 419 | str(file_size), 420 | "%.2f" % (float(chunk_end+1) 421 | / float(file_size)*100)), 422 | end='\r') 423 | chunk_start = chunk_end+1 424 | chunk_end += CHUNK_SIZE 425 | if chunk_end+1 >= file_size: 426 | chunk_end = file_size - 1 427 | 428 | logger.info(response.status_code) 429 | logger.info(response.text) 430 | 431 | data = json.loads(response.text) 432 | if ('file' in data and 'hashes' in data['file']): 433 | server_hash = data['file']['hashes']['sha1Hash'] 434 | else: 435 | server_hash = "None" 436 | 437 | logger.info("SHA1 local:"+cur_file_hash.hexdigest()) 438 | logger.info("SHA1 remote:"+server_hash) 439 | if (cur_file_hash.hexdigest() == server_hash.lower()): 440 | print("\nUpload of file {} complete". 441 | format(os.path.basename(file_name))) 442 | return 443 | cur_attempt += 1 444 | logger.warning("Hash of uploaded file does " 445 | "not match server. Attempting again") 446 | # If it doesn't match, we need to replace the existing file now 447 | payload["@name.conflictBehavior"] = "replace" 448 | 449 | if (cur_file_hash.hexdigest() != server_hash.lower()): 450 | raise RuntimeError("Hash of uploaded file does " 451 | "not match server.") 452 | 453 | def get_upload_status(self, url): 454 | status_codes = (requests.codes.ok,) 455 | r = (self. http_request(url=url, 456 | request_type=RequestType.GET, 457 | status_codes=status_codes, 458 | use_access_token=True, 459 | action_string="Get upload status", 460 | max_tries=10)) 461 | data = json.loads(r.text) 462 | return data 463 | 464 | def download_helper(self, url, local_path): 465 | logger = logging.getLogger("multidrive") 466 | 467 | NUM_ATTEMPTS = 5 468 | cur_attempt = 1 469 | while True: 470 | cur_attempt += 1 471 | with open(local_path, "wb") as f: 472 | 473 | logger.info("URL to save file is: "+url) 474 | 475 | status_codes = (requests.codes.ok,) 476 | severe_status_codes = (requests.codes.bandwidth_limit_exceeded, 477 | requests.codes.service_unavailable) 478 | try: 479 | r = (self. 480 | http_request(url=url, 481 | request_type=RequestType.GET, 482 | status_codes=status_codes, 483 | stream=True, 484 | severe_status_codes=severe_status_codes, 485 | use_access_token=True, 486 | action_string="Download file", 487 | max_tries=10, 488 | timeout=120)) 489 | 490 | size = 0 491 | cur_file_hash = hashlib.sha1() 492 | for chunk in r.iter_content(chunk_size=4*1024*1024): 493 | if chunk: # filter out keep-alive new chunks 494 | cur_file_hash.update(chunk) 495 | f.write(chunk) 496 | f.flush() 497 | size = size + 1 498 | if size % 200 == 0: 499 | logger.info(str(size*4) + "MB written") 500 | os.fsync(f.fileno()) 501 | except (ConnectionResetError, 502 | requests.exceptions.ConnectionError) as err: 503 | if cur_attempt < NUM_ATTEMPTS: 504 | logger.warning("Connection Error: %s" % err) 505 | continue 506 | raise err 507 | return cur_file_hash.hexdigest() 508 | 509 | def download_item(self, cur_file, destination=None, overwrite=False, 510 | create_folder=False): 511 | logger = logging.getLogger("multidrive") 512 | local_path = cur_file['name'] 513 | if destination is not None: 514 | local_path = os.path.join(destination, local_path) 515 | 516 | if 'folder' in cur_file: 517 | if not os.path.exists(local_path): 518 | # Add proper error message here? 519 | os.mkdir(local_path) 520 | return (local_path, cur_file['lastModifiedDateTime']) 521 | 522 | if os.path.isdir(local_path): 523 | raise RuntimeError("Local destination is a folder") 524 | if overwrite is False and os.path.isfile(local_path): 525 | raise RuntimeError("Local file {} exists. Enable overwrite " 526 | "option to continue.".format(local_path)) 527 | url = self.onedrive_url_root+"/drive/items/"+cur_file['id']+"/content" 528 | 529 | NUM_ATTEMPTS = 5 530 | cur_attempt = 1 531 | while cur_attempt <= NUM_ATTEMPTS: 532 | 533 | cur_file_hash = self.download_helper(url, local_path) 534 | 535 | # API documentation states that hashes may not be available until 536 | # after Item is downloaded 537 | if 'sha1Hash' not in cur_file['file']['hashes']: 538 | cur_file = self.get_item(item_id=cur_file['id']) 539 | remote_hash = cur_file['file']['hashes']['sha1Hash'] 540 | 541 | cur_attempt += 1 542 | if (cur_file_hash == remote_hash.lower()): 543 | break 544 | logger.warning("Hash of downloaded file does " 545 | "not match server. Attempting again") 546 | 547 | if (cur_file_hash != remote_hash.lower()): 548 | raise RuntimeError("Hash of downloaded file does " 549 | "not match server.") 550 | 551 | lastModifiedDateTimeString = cur_file['lastModifiedDateTime'] 552 | modifiedDate = parse(lastModifiedDateTimeString) 553 | 554 | os.utime(local_path, (time.mktime(modifiedDate.timetuple()), 555 | time.mktime(modifiedDate.timetuple()))) 556 | 557 | print(local_path + " has been saved to disk") 558 | # TODO: deal with return values. 559 | return (local_path, lastModifiedDateTimeString) 560 | 561 | def download(self, file_path, destination=None, overwrite=False): 562 | print("Download {} OneDrive Storage Service".format(file_path)) 563 | 564 | cur_file = self.get_item(item_path=file_path) 565 | if 'folder' in cur_file: 566 | raise RuntimeError("Remote destination is a folder") 567 | return self.download_item(cur_file, destination, overwrite) 568 | 569 | def is_folder(self, folder_path): 570 | result = self.get_item(item_path=folder_path) 571 | if result is None: 572 | return False 573 | return "folder" in result 574 | 575 | def get_item(self, item_path=None, item_id=None): 576 | logger = logging.getLogger("multidrive") 577 | 578 | if item_path is not None: 579 | if item_id is not None: 580 | raise RuntimeError("Just one of item_path and item_id " 581 | "should be specified") 582 | if item_path.endswith('/'): 583 | item_path = item_path[:-1] 584 | 585 | url = (self.onedrive_url_root+"/drive/root:/" + 586 | urllib.parse.quote(item_path)) 587 | if self.__app_folder__: 588 | url = (self.onedrive_url_root+"/drive/special/approot:/" + 589 | urllib.parse.quote(item_path)) 590 | elif item_id is not None: 591 | url = self.onedrive_url_root+"/drive/items/" + item_id 592 | else: 593 | raise RuntimeError("One of item_path and item_id " 594 | "should be specified") 595 | status_codes = (requests.codes.ok, 596 | requests.codes.not_found) 597 | 598 | response = self.http_request(url=url, 599 | request_type=RequestType.GET, 600 | status_codes=status_codes, 601 | use_access_token=True, 602 | action_string="Get Item", 603 | max_tries=8) 604 | 605 | if response.status_code == requests.codes.not_found: 606 | logger.info("Item not found: " + item_path) 607 | return None 608 | 609 | return json.loads(response.text) 610 | 611 | def create_folder(self, folder_path): 612 | logger = logging.getLogger("multidrive") 613 | 614 | if folder_path.endswith('/'): 615 | folder_path = folder_path[:-1] 616 | 617 | split_path = folder_path.split('/') 618 | cur_path = "" 619 | while len(split_path) > 0: 620 | 621 | prev_path = cur_path 622 | cur_item = split_path.pop(0) 623 | if len(cur_path) is 0: 624 | cur_path += cur_item 625 | else: 626 | cur_path += "/"+cur_item 627 | if self.is_folder(cur_path): 628 | continue 629 | 630 | logger.info("prev_path: " + prev_path) 631 | logger.info("cur_item: " + cur_item) 632 | logger.info("cur_path: " + cur_path) 633 | headers = {'Content-Type': "application/json"} 634 | 635 | payload = {} 636 | payload["name"] = cur_item 637 | payload["folder"] = {} 638 | 639 | url = "" 640 | if prev_path == "": 641 | url = self.onedrive_url_root+"/drive/root/children" 642 | if self.__app_folder__: 643 | url = (self.onedrive_url_root + 644 | "/drive/special/approot/children") 645 | else: 646 | url = (self.onedrive_url_root+"/drive/root:/" + 647 | urllib.parse.quote(prev_path)+":/children") 648 | if self.__app_folder__: 649 | url = (self.onedrive_url_root+"/drive/special/approot:/" + 650 | urllib.parse.quote(prev_path)+":/children") 651 | logger.info("url: " + url) 652 | 653 | response = self.http_request(url=url, 654 | request_type=RequestType.POST, 655 | status_codes=(requests.codes.ok, 656 | requests.codes.created, 657 | requests.codes.accepted, 658 | requests.codes. 659 | not_found), 660 | headers=headers, 661 | data=json.dumps(payload), 662 | use_access_token=True, 663 | action_string="Create Folder", 664 | max_tries=6) 665 | 666 | if response.status_code == requests.codes.not_found: 667 | logger.info("Item not found: " + prev_path) 668 | return False 669 | return True 670 | 671 | def list_folder(self, folder_path): 672 | base_folder = None 673 | if folder_path is None: 674 | folder_path = "" 675 | base_folder = self.get_item(item_path=folder_path) 676 | 677 | if "folder" not in base_folder: 678 | raise RuntimeError("Invalid folder: "+folder_path) 679 | 680 | folder_list = self.get_folder_listing(base_folder, [], folder_path) 681 | return folder_list 682 | 683 | def get_folder_listing(self, cur_folder, path_list, current_path): 684 | logger = logging.getLogger("multidrive") 685 | 686 | print("Getting listing for {}".format(current_path)) 687 | result_list = [] 688 | if current_path.endswith('/'): 689 | current_path = current_path[:-1] 690 | url = (self.onedrive_url_root+"/drive/root:/" + 691 | urllib.parse.quote(current_path)+":/children") 692 | if self.__app_folder__: 693 | url = (self.onedrive_url_root+"/drive/special/approot:/" + 694 | urllib.parse.quote(current_path)+":/children") 695 | 696 | status_codes = (requests.codes.ok, 697 | requests.codes.not_found) 698 | 699 | response = self.http_request(url=url, 700 | request_type=RequestType.GET, 701 | status_codes=status_codes, 702 | use_access_token=True, 703 | action_string="Get Folder Listing", 704 | max_tries=8) 705 | 706 | if response.status_code == requests.codes.not_found: 707 | logger.info("Item not found: " + current_path) 708 | raise RuntimeError("Item not found. Possible bad path: " + 709 | current_path) 710 | 711 | data = json.loads(response.text) 712 | 713 | for current_item in data['value']: 714 | result_list.append((current_item, path_list)) 715 | if "folder" in current_item: 716 | new_list = list(path_list) 717 | new_list.append(current_item['name']) 718 | if self.__app_folder__ and len(current_path) == 0: 719 | result_list.extend( 720 | self.get_folder_listing(current_item, new_list, 721 | current_item['name'])) 722 | else: 723 | result_list.extend( 724 | self.get_folder_listing(current_item, new_list, 725 | current_path+'/' + 726 | current_item['name'])) 727 | return result_list 728 | 729 | def get_file_name(self, file): 730 | return file['name'] 731 | 732 | def is_folder_from_file_type(self, file): 733 | return "folder" in file 734 | 735 | # Formatting code from http://stackoverflow.com/questions/1094841/ 736 | def format_bytes(self, num, suffix='B'): 737 | for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: 738 | if abs(num) < 1024.0: 739 | return "%3.2f%s%s" % (num, unit, suffix) 740 | num /= 1024.0 741 | return "%.2f%s%s" % (num, 'Yi', suffix) 742 | 743 | def get_quota(self): 744 | 745 | url = self.onedrive_url_root+"/drive" 746 | 747 | status_codes = (requests.codes.ok,) 748 | 749 | response = self.http_request(url=url, 750 | request_type=RequestType.GET, 751 | status_codes=status_codes, 752 | use_access_token=True, 753 | action_string="Get OneDrive Metadata", 754 | max_tries=8) 755 | data = json.loads(response.text) 756 | 757 | total_quota = data['quota']['total'] 758 | used_quota = data['quota']['used'] 759 | remaining_quota = data['quota']['remaining'] 760 | trashed_quota = data['quota']['deleted'] 761 | percentage = float(used_quota)/total_quota*100 762 | result = (("Total quota: {}\n" 763 | "Used quota: {}\n" 764 | "Remaining Quota: {}\n" 765 | "Data in Recycle bin: {}\n" 766 | "Percentage Used {}%") 767 | .format(self.format_bytes(total_quota), 768 | self.format_bytes(used_quota), 769 | self.format_bytes(remaining_quota), 770 | self.format_bytes(trashed_quota), 771 | float("{0:.2f}". 772 | format(percentage)))) 773 | return result 774 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------