├── MANIFEST.in ├── requirments.txt ├── files.txt ├── onedrivecmd ├── __init__.py ├── utils │ ├── __init__.py │ ├── helper_print.py │ ├── static.py │ ├── helper_file.py │ ├── downloader.py │ ├── helper_item.py │ ├── arguments.py │ ├── uploader.py │ ├── session.py │ └── actions.py └── onedrivecmd.py ├── .gitignore ├── setup.py ├── README.md ├── README.rst └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | -------------------------------------------------------------------------------- /requirments.txt: -------------------------------------------------------------------------------- 1 | onedrivesdk < 2 2 | progress 3 | requests -------------------------------------------------------------------------------- /files.txt: -------------------------------------------------------------------------------- 1 | /Library/Python/2.7/site-packages/OnedriveCMD-0.1.0-py2.7.egg 2 | /usr/local/bin/onedrivecmd 3 | -------------------------------------------------------------------------------- /onedrivecmd/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | # ------- 4 | # Pythons 5 | # ------- 6 | 7 | # Syntax sugar. 8 | _ver = sys.version_info 9 | 10 | #: Python 2.x? 11 | is_py2 = (_ver[0] == 2) 12 | 13 | #: Python 3.x? 14 | is_py3 = (_ver[0] == 3) 15 | 16 | # --------- 17 | # Specifics 18 | # --------- 19 | 20 | if is_py2: 21 | from itertools import izip_longest as zip_longest 22 | from StringIO import StringIO 23 | 24 | builtin_str = str 25 | bytes = str 26 | str = unicode 27 | basestring = basestring 28 | numeric_types = (int, long, float) 29 | 30 | 31 | elif is_py3: 32 | from itertools import zip_longest 33 | from io import StringIO 34 | 35 | builtin_str = str 36 | str = str 37 | bytes = bytes 38 | basestring = (str, bytes) 39 | numeric_types = (int, float) 40 | -------------------------------------------------------------------------------- /onedrivecmd/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | try: 4 | text_type = unicode 5 | except NameError: # py3 6 | text_type = str 7 | 8 | def convert_utf8_dict_to_dict(dict_to_convert): 9 | """convert the utf-8 coded JSON dict 10 | coming back from requests to a normal decoded one 11 | """ 12 | if isinstance(dict_to_convert, dict): 13 | try: 14 | return dict( 15 | (convert_utf8_dict_to_dict(key), convert_utf8_dict_to_dict(value)) for key, value in 16 | dict_to_convert.iteritems()) 17 | except AttributeError: # python3 18 | return dict( 19 | (convert_utf8_dict_to_dict(key), convert_utf8_dict_to_dict(value)) for key, value in 20 | dict_to_convert.items()) 21 | elif isinstance(dict_to_convert, list): 22 | return [convert_utf8_dict_to_dict(element) for element in dict_to_convert] 23 | elif isinstance(dict_to_convert, str): 24 | return dict_to_convert 25 | elif isinstance(dict_to_convert, text_type): 26 | return dict_to_convert.encode('ascii', 'ignore') 27 | else: 28 | return dict_to_convert -------------------------------------------------------------------------------- /onedrivecmd/utils/helper_print.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | # Author: Dict Xiong -- 4 | # Purpose: print logs which may be useful to users and us maintainers too :) 5 | # Created: 03/29/2019 6 | 7 | import time 8 | 9 | def print_error(error_type="",note=""): 10 | """ str->None 11 | 12 | Print structured error note. 13 | Chars between '\033[31m' and '\033[0m' 14 | will be printed in red. 15 | """ 16 | 17 | if error_type == "": 18 | print("\033[31m"+note+"\033[0m") 19 | elif note == "": 20 | print("\033[31m"+error_type+" error.\033[0m") 21 | else: 22 | print("\033[31m"+error_type+" error:\033[0m "+note) 23 | 24 | def print_time(): 25 | """ 26 | 27 | Print time now like: 28 | [08:00:00] 29 | """ 30 | print("["+time.strftime("%H:%M:%S",time.localtime())+"]") 31 | 32 | def print_job_binary(source,dest): 33 | """str,str->None 34 | 35 | Print a job that will deal with two files 36 | i.e. 'put' and 'get'. 37 | Chars between '\033[36m' and '\033[0m' 38 | will be printed in blue. 39 | """ 40 | print("\033[36m"+source+"\033[0m ==> \033[36m"+dest+"\033[0m") 41 | -------------------------------------------------------------------------------- /onedrivecmd/utils/static.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: Static varibles for onedrivecmd 5 | # Created: 09/24/2016 6 | 7 | 8 | global VER, redirect_uri, client_secret, client_id, api_base_url, scopes, discovery_uri, auth_server_url, auth_token_url 9 | 10 | VER = 'OnedriveCMD V0.1.8' 11 | 12 | # If you are not sure whether this is safe, 13 | # you can register your own APP and use your own URL. 14 | # Don't just change it: you will have error. 15 | redirect_uri = 'https://od.cnbeining.com' 16 | 17 | ## Normal 18 | client_secret_normal = 'RQdGA24FctsiBGuP8v3juea' 19 | client_id_normal = 'aeba6391-92fd-437d-a9d9-33a258b96c4e' 20 | api_base_url = 'https://api.onedrive.com/v1.0/' 21 | scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite'] 22 | 23 | ## Business 24 | discovery_uri = 'https://api.office.com/discovery/' 25 | auth_server_url = 'https://login.microsoftonline.com/common/oauth2/authorize', 26 | auth_token_url = 'https://login.microsoftonline.com/common/oauth2/token' 27 | 28 | # If you are working with Office 365 you may want to create your own app 29 | # and change the following: 30 | # You can still use https://od.cnbeining.com as redirect URL. 31 | client_id_business = '6fdb55b4-c905-4612-bd23-306c3918217c' 32 | client_secret_business = 'HThkLCvKhqoxTDV9Y9uS+EvdQ72fbWr/Qrn2PFBZ/Ow=' 33 | 34 | if __name__ == '__main__': 35 | pass 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | *.pickle 92 | *.json 93 | 94 | .idea/ 95 | 96 | #vim swap files 97 | *.swp 98 | -------------------------------------------------------------------------------- /onedrivecmd/onedrivecmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: A command line client for OneDrive 5 | # Created: 09/23/2016 6 | 7 | try: 8 | from onedrivecmd.utils.actions import * 9 | from onedrivecmd.utils.arguments import parse_args 10 | from onedrivecmd.utils.session import * 11 | from onedrivecmd.utils.static import * 12 | from onedrivecmd.utils.uploader import * 13 | from onedrivecmd.utils.helper_item import * 14 | from onedrivecmd.utils.helper_file import * 15 | from onedrivecmd.utils.helper_print import * 16 | except ImportError: 17 | from .utils.actions import * 18 | from .utils.arguments import parse_args 19 | from .utils.session import * 20 | from .utils.static import * 21 | from .utils.uploader import * 22 | from .utils.helper_item import * 23 | from .utils.helper_file import * 24 | from .utils.helper_print import * 25 | 26 | def main(): 27 | """None->None 28 | 29 | Main entrance of the script. 30 | 31 | Init the script, 32 | Parse arguments, 33 | Call the right action. 34 | """ 35 | ## parse arguments 36 | args = parse_args() 37 | 38 | # mock client 39 | http_provider = onedrivesdk.HttpProvider() 40 | auth_provider = onedrivesdk.AuthProvider 41 | 42 | client = onedrivesdk.OneDriveClient 43 | 44 | ## Call action 45 | # Init 46 | if args.mode == 'init' or args.mode == 'init_business': 47 | client = do_init(client, args) 48 | 49 | # We assume that the init is successful 50 | print('Logged in, saving information...') 51 | 52 | save_session(client, path = args.conf) 53 | return 54 | 55 | ## Load session 56 | # If the mode is not init, there has to be a working session 57 | # located at the conf path. 58 | client = load_session(client, path = args.conf) 59 | 60 | # get 61 | if args.mode == 'get': 62 | do_get(client, args) 63 | 64 | elif args.mode == 'list': 65 | do_list(client, args) 66 | 67 | elif args.mode == 'put': 68 | do_put(client, args) 69 | 70 | elif args.mode == 'share': 71 | do_share(client, args) 72 | 73 | elif args.mode == 'direct': 74 | do_direct(client, args) 75 | 76 | elif args.mode == 'delete': 77 | do_delete(client, args) 78 | 79 | elif args.mode == 'mkdir': 80 | do_mkdir(client, args) 81 | 82 | elif args.mode == 'move': 83 | do_move(client, args) 84 | 85 | elif args.mode == 'remote': 86 | do_remote(client, args) 87 | 88 | elif args.mode == 'search': 89 | do_search(client, args) 90 | 91 | elif args.mode == 'quota': 92 | do_quota(client, args) 93 | 94 | 95 | if __name__ == '__main__': 96 | main() 97 | -------------------------------------------------------------------------------- /onedrivecmd/utils/helper_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: File, path and OS related helpers for onedrivecmd 5 | # Created: 09/24/2016 6 | 7 | import sys 8 | import os 9 | 10 | # compact Python 2.* 11 | if sys.version_info < (3, 0): 12 | input = raw_input 13 | from urllib import unquote 14 | else: 15 | from urllib.parse import unquote 16 | 17 | 18 | ## os related 19 | def execute_cmd(cmd): 20 | """str->int 21 | 22 | Execute a command, 23 | send the command output to the screen, 24 | give a simple warning if the command failed, 25 | return the exit code of the command. 26 | """ 27 | try: 28 | os.system(cmd.decode("utf-8").encode(sys.stdout.encoding)) 29 | # python 3 30 | except AttributeError: 31 | os.system(cmd) 32 | 33 | 34 | ## file related 35 | def file_read_seek_len(filename, from_byte, step_byte): 36 | """str, int, int->byte 37 | 38 | Read a file from particular byte to somewhere. 39 | 40 | Used for multi thread uploading. 41 | """ 42 | with open(filename, 'rb') as f: 43 | f.seek(from_byte) 44 | return f.read(step_byte) 45 | 46 | 47 | ## path related 48 | def path_to_name(path): 49 | """str->str 50 | 51 | Strip a file path to filename, 52 | which is quoted so Linux would not complain. 53 | 54 | Works with both od:/ and real path. 55 | """ 56 | return os.path.basename(path) 57 | 58 | 59 | def path_to_remote_path(path): 60 | """str->str 61 | 62 | Return a remote path or local path, with filename striped. 63 | 64 | Works with both od:/ and real path. 65 | """ 66 | if path.startswith('od:'): 67 | path = path[3:] 68 | 69 | return os.path.split(path)[0] 70 | 71 | 72 | def get_remote_path_by_item(item): 73 | """str->str 74 | 75 | Get the remote path in string for any item, 76 | including the root folder. 77 | 78 | /drive/root: cannot exist or the SDK shall throw error. 79 | """ 80 | try: 81 | info_dict = item.to_dict() 82 | 83 | except AttributeError: 84 | # only root node does not have this attribute 85 | return '/' 86 | 87 | try: 88 | return unquote(item.to_dict()['parentReference']['path'] + '/' + item.to_dict()['name']).encode( 89 | 'utf-8').replace('/drive/root:', '') 90 | except: 91 | return unquote(item.to_dict()['parentReference']['path'] + '/' + item.to_dict()['name']).replace('/drive/root:', 92 | '') 93 | 94 | 95 | def dict_merge(a, b): 96 | c = a.copy() 97 | c.update(b) 98 | return c 99 | 100 | 101 | def sizeof_fmt(num, suffix = 'B'): 102 | '''int, str->str 103 | 104 | Format file size as human readable. 105 | 106 | From: 107 | https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size 108 | ''' 109 | for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: 110 | if abs(num) < 1024.0: 111 | return "%3.1f%s%s" % (num, unit, suffix) 112 | num /= 1024.0 113 | return "%.1f%s%s" % (num, 'Yi', suffix) 114 | 115 | 116 | if __name__ == '__main__': 117 | pass 118 | -------------------------------------------------------------------------------- /onedrivecmd/utils/downloader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Dict Xiong -- 4 | # Purpose: File downloader 5 | # Create: 04/01/2019 6 | 7 | from progress.bar import Bar 8 | import requests 9 | 10 | try: 11 | from static import * 12 | from helper_file import * 13 | from helper_print import * 14 | from helper_item import * 15 | from session import * 16 | except ImportError: 17 | from .static import * 18 | from .helper_file import * 19 | from .helper_print import * 20 | from .helper_item import * 21 | from .session import * 22 | 23 | def download_self(client, remote_path="", local_dir="", chunksize = 10247680, url=False, hack=False): 24 | """ OneDriveClient, str, str, int, Bool -> Bool 25 | 26 | Download a file with in our own way 27 | with progress bar. 28 | This should be better than the built-in one 29 | since that one does not comes with any bar, not even a callback point. 30 | From http://stackoverflow.com/a/20943461/2946714 31 | This is slower than I thought. 32 | 33 | """ 34 | if not local_dir.endswith("/"): 35 | local_dir+="/" 36 | 37 | if remote_path.endswith("/") and remote_path != "/": 38 | remote_path=remote_path[:-1] 39 | 40 | item=get_remote_item(client, path=remote_path) 41 | if item is None: 42 | print_error("Remote file", "File {path} does not exist!".format(path=remote_path)) 43 | return False 44 | 45 | if os.path.isfile(local_dir): 46 | print_error("File","The dest dir {dir} is a file!".format(dir=local_dir)) 47 | return None 48 | if not os.path.isdir(local_dir): 49 | os.makedirs(local_dir) 50 | 51 | if not item.folder: 52 | if token_time_to_live(client) < 50*60: 53 | refresh_token(client) 54 | # fetch the file [url, size] 55 | item_info=get_item_temp_download_info(item) 56 | # if only show thr url '-url' 57 | if url: 58 | print(remote_path+": "+item_info[0]) 59 | return True 60 | 61 | local_path=local_dir+path_to_name(remote_path) 62 | 63 | #Stamps 64 | print(" ") 65 | print_time() 66 | print_job_binary(remote_path,local_path) 67 | 68 | 69 | if not hack: 70 | r=requests.get(item_info[0], stream=True) 71 | if r.status_code > 201: 72 | print_error("Request",str(req.status_code)+" "+r.json()["error"]["message"]) 73 | return False 74 | total_length=int(item_info[1]) 75 | 76 | # bar init 77 | bar=Bar('Downloading', max = total_length / chunksize, suffix = '%(percent).1f%% - %(eta)ds') 78 | # Save file as chunk, upload Bar as chunk written 79 | with open(local_path, "wb") as f: 80 | for chunk in r.iter_content(chunk_size=chunksize): 81 | if chunk: 82 | f.write(chunk) 83 | f.flush() 84 | bar.next() 85 | bar.finish() 86 | else: 87 | cmd = 'aria2c -c -o "{local_name}" -s16 -x16 -k1M "{remote_link}"'.format(local_name=local_path, remote_link=item_info[0]) 88 | execute_cmd(cmd) 89 | else: 90 | new_local_dir=local_dir+path_to_name(remote_path) 91 | item=get_remote_folder_children(client,id=item.id) 92 | for i in item: 93 | download_self(client, remote_path+"/"+i.name, new_local_dir, chunksize, url, hack) 94 | return True 95 | 96 | -------------------------------------------------------------------------------- /onedrivecmd/utils/helper_item.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: Helpers for Item operations for onedrivecmd 5 | # Created: 09/24/2016 6 | 7 | import onedrivesdk 8 | 9 | from onedrivecmd.utils import convert_utf8_dict_to_dict 10 | 11 | try: 12 | from helper_file import * 13 | except ImportError: 14 | from .helper_file import * 15 | 16 | 17 | ### Helper functions 18 | 19 | ## item related 20 | def get_remote_item(client, path = '', id = ''): 21 | """str->A item 22 | 23 | Return a file/folder item. 24 | If item not exist at remote, return None. 25 | 26 | Only works with path OR id. 27 | """ 28 | try: 29 | if path != '': # check path 30 | path = od_path_to_api_path(path) 31 | if path.endswith("/") and path != "/": 32 | path=path[:-1] 33 | f = client.item(drive = 'me', path = path).get() 34 | elif id != '': # check id 35 | f = client.item(drive = 'me', id = id).get() 36 | 37 | except onedrivesdk.error.OneDriveError: 38 | # onedrivesdk.error.OneDriveError: itemNotFound - Item does not exist 39 | return None 40 | #if f.folder: 41 | # f = get_remote_folder_children(client, id = f.id) 42 | return f 43 | 44 | def get_remote_folder_children(client, path="", id=""): 45 | """client, str->item 46 | 47 | return children of a folder. 48 | work with path or id. 49 | """ 50 | try: 51 | if path != "": 52 | path = od_path_api_path(path) 53 | #f = client.item(drive="me", path=path).get() 54 | #if not f.folder: 55 | # return None 56 | if path.endswith("/") and path != "/": 57 | path=path[:-1] 58 | f = client.item(drive="me", path=path).children.get() 59 | elif id != "": 60 | #f = client.item(drive="me", id=id).get() 61 | #if not f.folder: 62 | # return None 63 | f = client.item(drive="me", id=id).children.get() 64 | else: 65 | return None 66 | except onedrivesdk.error.OneDriveError: 67 | return None 68 | return f 69 | 70 | 71 | def od_path_to_api_path(path): 72 | """str->str 73 | 74 | In case of mixing remote stuff and local stuff, 75 | I am requesting a od:/path/to/file/or/folder/1.txt like remote path. 76 | """ 77 | return (path[3:] if path.startswith('od:') else path) 78 | 79 | 80 | def get_item_temp_download_info(item): 81 | """onedrivesdk.model.item.Item->(str, int, str) 82 | 83 | Get the direct download link of a file item so 84 | we can use tools like aria2 or make our own download. 85 | 86 | This link is only vaild for a few minutes. 87 | 88 | Return: 89 | 90 | (URL, file_size) 91 | 92 | We cannot return a hash since only personal has SHA1, 93 | sometimes only quickXorHash. 94 | 95 | """ 96 | file_info = convert_utf8_dict_to_dict(item.to_dict()) 97 | return (file_info['@content.downloadUrl'], 98 | file_info['size'],) 99 | # file_info['file']['hashes']['sha1Hash'].encode('utf-8')) 100 | 101 | 102 | def get_bare_item_by_path(client, path = ''): 103 | """str->item 104 | 105 | Just return a Item object. 106 | 107 | If not exist, return None. 108 | """ 109 | return client.item(drive = 'me', 110 | path = path_to_remote_path(path) + '/' + path_to_name(path)) 111 | 112 | 113 | def get_search_item_list_single_page_by_url_rec(requests_session, access_token, url, item_list = []): 114 | req = requests_session.get(url, headers = 115 | {'Authorization': 'bearer {access_token}'.format(access_token = access_token), 116 | 'content-type': 'application/json'}) 117 | 118 | for json_item in req.json()['value']: 119 | item_list.append(json_item) 120 | 121 | if '@odata.nextLink' in req.json(): # multiple page 122 | return get_search_item_list_single_page_by_url_rec(requests_session, item['@odata.nextLink'], item_list) 123 | else: 124 | return item_list 125 | 126 | 127 | if __name__ == '__main__': 128 | pass 129 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """A setuptools based setup module. 2 | 3 | See: 4 | https://packaging.python.org/en/latest/distributing.html 5 | https://github.com/pypa/sampleproject 6 | """ 7 | 8 | # Always prefer setuptools over distutils 9 | from setuptools import setup, find_packages 10 | # To use a consistent encoding 11 | from codecs import open 12 | from os import path 13 | 14 | here = path.abspath(path.dirname(__file__)) 15 | 16 | # Get the long description from the README file 17 | with open(path.join(here, 'README.rst'), encoding='utf-8') as f: 18 | long_description = f.read() 19 | 20 | setup( 21 | name='OnedriveCMD', 22 | 23 | # Versions should comply with PEP440. For a discussion on single-sourcing 24 | # the version across setup.py and the project code, see 25 | # https://packaging.python.org/en/latest/single_source_version.html 26 | version='0.1.8.1', 27 | 28 | description='A command line client for Onedrive.', 29 | long_description=long_description, 30 | 31 | # The project's main homepage. 32 | url='https://github.com/cnbeining/onedrivecmd', 33 | 34 | # Author details 35 | author='Beining', 36 | author_email='i@cnbeining.com', 37 | 38 | # Choose your license 39 | license='GPLv3', 40 | 41 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 42 | classifiers=[ 43 | # How mature is this project? Common values are 44 | # 3 - Alpha 45 | # 4 - Beta 46 | # 5 - Production/Stable 47 | 'Development Status :: 4 - Beta', 48 | 49 | # Indicate who your project is intended for 50 | 'Intended Audience :: Developers', 51 | 'Intended Audience :: End Users/Desktop', 52 | 'Intended Audience :: Information Technology', 53 | 'Intended Audience :: System Administrators', 54 | 55 | 'Topic :: System :: Archiving :: Backup', 56 | 'Topic :: Utilities', 57 | 58 | # Pick your license as you wish (should match "license" above) 59 | 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 60 | 61 | # Specify the Python versions you support here. In particular, ensure 62 | # that you indicate whether you support Python 2, Python 3 or both. 63 | 'Programming Language :: Python :: 2', 64 | 'Programming Language :: Python :: 2.7', 65 | 'Programming Language :: Python :: 3', 66 | 'Programming Language :: Python :: 3.3', 67 | 'Programming Language :: Python :: 3.4', 68 | 'Programming Language :: Python :: 3.5', 69 | 'Programming Language :: Python :: 3.6', 70 | ], 71 | 72 | # What does your project relate to? 73 | keywords='onedrive backup', 74 | 75 | # You can just specify the packages manually here if your project is 76 | # simple. Or you can use find_packages(). 77 | packages=find_packages(), 78 | 79 | # Alternatively, if you want to distribute just a my_module.py, uncomment 80 | # this: 81 | # py_modules=["my_module"], 82 | 83 | # List run-time dependencies here. These will be installed by pip when 84 | # your project is installed. For an analysis of "install_requires" vs pip's 85 | # requirements files see: 86 | # https://packaging.python.org/en/latest/requirements.html 87 | install_requires=['progress', 'onedrivesdk', 'requests'], 88 | 89 | # List additional groups of dependencies here (e.g. development 90 | # dependencies). You can install these using the following syntax, 91 | # for example: 92 | # $ pip install -e .[dev,test] 93 | extras_require={ 94 | 'dev': ['check-manifest'], 95 | 'test': ['coverage'], 96 | }, 97 | 98 | # If there are data files included in your packages that need to be 99 | # installed, specify them here. If using Python 2.6 or less, then these 100 | # have to be included in MANIFEST.in as well. 101 | package_data={}, 102 | 103 | # Although 'package_data' is the preferred approach, in some case you may 104 | # need to place data files outside of your packages. See: 105 | # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa 106 | # In this case, 'data_file' will be installed into '/my_data' 107 | data_files=[], 108 | 109 | # To provide executable scripts, use entry points in preference to the 110 | # "scripts" keyword. Entry points provide cross-platform support and allow 111 | # pip to create the appropriate form of executable for the target platform. 112 | entry_points={ 113 | 'console_scripts': [ 114 | 'onedrivecmd=onedrivecmd.onedrivecmd:main', 115 | ], 116 | }, 117 | ) 118 | -------------------------------------------------------------------------------- /onedrivecmd/utils/arguments.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: Argument parser for onedrivecmd 5 | # Created: 09/24/2016 6 | 7 | import argparse 8 | import os 9 | 10 | try: 11 | from static import * 12 | except ImportError: 13 | from .static import * 14 | 15 | 16 | ### Arguments 17 | def parse_args(): 18 | """None->??? 19 | 20 | Argument parser of the script. 21 | 22 | Supported arguments: 23 | 24 | --version: Print version 25 | 26 | Actions, these are mutually exclusive: 27 | 28 | list: List the remote dir's content 29 | 30 | get: Fetch a remote file and put the file in a local location 31 | 32 | put: Upload a local file to the remote location 33 | 34 | delete: Delete a remote file/folder 35 | 36 | mkdir: Make a folder at remote location 37 | 38 | move: Move a remote file to a remote location 39 | 40 | sync: TODO 41 | 42 | remote: remote download a link to drive 43 | """ 44 | 45 | ## Parser Init 46 | parser = argparse.ArgumentParser() 47 | 48 | ## Basic functions 49 | parser.add_argument('--version', action = 'version', version = VER) 50 | 51 | # Set the config file location 52 | parser.add_argument('-chunk', 53 | default = 62914560, 54 | type = int, 55 | help = 'Set the chunk size when uploading, use with -hack, must be times of 327680. Max is 62914560.') 56 | 57 | # Set the config file location 58 | parser.add_argument('-conf', 59 | default = os.path.expanduser('~/.onedrive.json'), 60 | help = 'Set the location of config file') 61 | 62 | # Whether Force hard delete or overwrite, default if False 63 | parser.add_argument('-force', 64 | action = 'store_true', 65 | default = False, 66 | help = 'Force delete or overwrite when performing') 67 | 68 | # Whether Recursive listing folder, default if False 69 | parser.add_argument('-recursive', 70 | action = 'store_true', 71 | default = False, 72 | help = 'Recursively listing folder') 73 | 74 | # TODO: asc when listing folder and searching. But by which field? 75 | parser.add_argument('-asc', 76 | action = 'store_true', 77 | default = False, 78 | help = 'Recursively listing folder') 79 | 80 | # TODO: desc when listing folder and searching 81 | parser.add_argument('-desc', 82 | action = 'store_true', 83 | default = False, 84 | help = 'Recursively listing folder') 85 | 86 | # Use downloader to download, or use multi-thread upload(highly exp) 87 | parser.add_argument('-hack', 88 | action = 'store_true', 89 | default = False, 90 | help = '') 91 | 92 | # Only output the download links 93 | parser.add_argument('-url', 94 | action = 'store_true', 95 | default = False, 96 | help = 'Only display the download link(s), temp one') 97 | 98 | # Set the logging level 99 | parser.add_argument('-verbose', 100 | action = 'store', 101 | choices = ['DEBUG', 'INFO', 'WARNING', 'ERROR'], 102 | default = 'WARNING', 103 | help = 'Set the logging level') 104 | 105 | # Show full path instead of short one while listing 106 | parser.add_argument('-fullpath', 107 | action = 'store_true', 108 | default = False, 109 | help = 'Show full path instead of short one while listing') 110 | 111 | ## Script actions 112 | # Set mutually exclusive actions 113 | parser.add_argument('mode', 114 | choices = ['init_business', 'init', 'get', 'list', 'put', 'delete', 'mkdir', 'move', 'remote', 115 | 'quota', 'share', 'direct', 'search'], 116 | help = """Action to be done.\n 117 | init: Use OAuth to setup the programme\n 118 | init_business: Use OAuth to setup the programme with Office 365\n 119 | get: get a remote item to local\n 120 | list: list a remote folder\n 121 | put: put a local item to remote\n 122 | delete: delete a remote item\n 123 | mkdir: make a folder at remote\n 124 | move: move a remote item to a remote location\n 125 | remote: download a remote link to drive\n 126 | search: search from your drive 127 | share: get the download link of the file/folder\n 128 | direct: get the direct download link of the file\n 129 | quota: Get the quota of the drive""") 130 | 131 | # Return the parsed content 132 | args, rest = parser.parse_known_args() 133 | args.rest = rest 134 | return args 135 | 136 | 137 | if __name__ == '__main__': 138 | pass 139 | -------------------------------------------------------------------------------- /onedrivecmd/utils/uploader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: File uploader for onedrivecmd 5 | # Created: 09/24/2016 6 | 7 | import json 8 | from progress.bar import Bar 9 | import requests 10 | from collections import OrderedDict 11 | 12 | try: 13 | from static import * 14 | from helper_file import * 15 | from helper_item import * 16 | from session import * 17 | from helper_print import * 18 | except ImportError: 19 | from .static import * 20 | from .helper_file import * 21 | from .helper_item import * 22 | from .session import * 23 | from .helper_print import * 24 | 25 | 26 | ## Upload related 27 | def upload_one_piece(uploadUrl = '', token = '', source_file = '', range_this = [], file_size = 0, 28 | requests_session = None): 29 | """list->int 30 | 31 | Post one piece of file to Onedrive via API. 32 | """ 33 | if requests_session is None: 34 | requests_session = requests.Session() 35 | # this is how everything calculated 36 | content_length = range_this[1] - range_this[0] + 1 37 | 38 | file_piece = file_read_seek_len(source_file, range_this[0], content_length) 39 | 40 | # Since we are setting up the header by ourselves, we must make sure 41 | # the DATA TYPE of the headers are correct (i.e., everything in string) 42 | # or sometimes requests is not able to do 43 | # auto data type converting. 44 | # On OS X everything works fine; Ubuntu would throw an 45 | # Header value 10485760 must be of type str or bytes, not 46 | headers = {'Authorization': 'bearer {access_token}'.format(access_token = token), 47 | 'Content-Range': 'bytes {start}-{to}/{total}'.format(start = range_this[0], 48 | to = range_this[1], 49 | total = str(file_size)), 50 | 'Content-Length': str(content_length), } 51 | 52 | req = requests_session.put(uploadUrl, 53 | data = file_piece, 54 | headers = headers) 55 | 56 | return req.status_code 57 | 58 | 59 | def upload_self(client, source_file = '', dest_path = '', chunksize = 10247680): 60 | """OneDriveClient, str, str, int->Bool 61 | 62 | Upload a file/dir via the API, instead of the SDK. 63 | 64 | Ref: https://dev.onedrive.com/items/upload_post.htm 65 | """ 66 | ## get upload URL 67 | if not dest_path.endswith('/'): 68 | dest_path += '/' 69 | 70 | if source_file.endswith('/') and source_file != "/": 71 | source_file=source_file[:-1] 72 | 73 | # check if it's a file 74 | if os.path.isfile(source_file): 75 | # Prepare API call 76 | # token expires in 3600s, just refresh it if TTL<50min. 77 | if token_time_to_live(client) < 50*60: 78 | refresh_token(client) 79 | 80 | dest_path = ('' if path_to_remote_path(dest_path)=='/' else path_to_remote_path(dest_path)) + '/' + path_to_name(source_file) 81 | # Stamps 82 | print(" ") 83 | print_time() 84 | print_job_binary(source_file,"od:"+dest_path) 85 | 86 | info_json = json.dumps({'item': OrderedDict([('@name.conflictBehavior', 'rename'), ('name', path_to_name(source_file))])}) 87 | 88 | api_url = client.base_url + 'drive/root:{dest_path}:/upload.createSession'.format(dest_path = dest_path) 89 | 90 | req = requests.post(api_url, 91 | data = info_json, 92 | headers = {'Authorization': 'bearer {access_token}'.format(access_token = get_access_token(client)), 93 | 'content-type': 'application/json'}) 94 | 95 | if req.status_code > 201: 96 | # Avoid print message exaclty after the bar. 97 | print(" ") 98 | print_error("Request", str(req.status_code)+" "+req.json()['error']['message']) 99 | return False 100 | 101 | req = convert_utf8_dict_to_dict(req.json()) 102 | 103 | uploadUrl = req['uploadUrl'] 104 | 105 | # filesize cannot > 10GiB 106 | file_size = os.path.getsize(source_file) 107 | 108 | # API may be unable to cope with empty files, as I tested by uploading with range_list [[0,0]]. 109 | if file_size==0: 110 | print("Empty file detected, trying SDK...") 111 | client.item(drive = "me", path = dest_path).upload_async(source_file) 112 | return True 113 | 114 | range_list = [[i, i + chunksize - 1] for i in range(0, file_size, chunksize)] 115 | range_list[-1][-1] = file_size - 1 116 | 117 | # Upload with a progress bar 118 | bar = Bar('Uploading', max = len(range_list), suffix = '%(percent).1f%% - %(eta)ds') 119 | bar.next() # nessesery to init the Bar 120 | 121 | # Session reuse when uploading, hopefully will kill some overhead 122 | requests_session = requests.Session() 123 | for i in range_list: 124 | for j in range(0,6): 125 | if j==5: 126 | print_error(note="Trial limit exceeded, skip this file.") 127 | return False 128 | try: 129 | upload_one_piece(uploadUrl = uploadUrl, token = get_access_token(client), source_file = source_file, 130 | range_this = i, file_size = file_size, requests_session = requests_session) 131 | break 132 | except Exception as e: 133 | print_error("Upload",str(e)+", will try again later.") 134 | continue 135 | bar.next() 136 | 137 | bar.finish() 138 | # So it's a dir, upload it recursively. 139 | else: 140 | new_dest_path=dest_path+path_to_name(source_file) 141 | for new_source_file in os.listdir(source_file): 142 | upload_self(client, source_file+"/"+new_source_file, new_dest_path, chunksize) 143 | return True 144 | 145 | def upload_self_hack(client, source_file = '', dest_path = ''): 146 | """OneDriveClient, str, str->Bool 147 | 148 | Upload a file/dir via the SDK. 149 | """ 150 | 151 | if not dest_path.endswith('/'): 152 | dest_path += '/' 153 | 154 | if source_file.endswith('/'): 155 | source_file=source_file[:-1] 156 | 157 | # check if it's a file 158 | if os.path.isfile(source_file): 159 | # token refresh 160 | if token_time_to_live(client) < 50*60: 161 | refresh_token(client) 162 | 163 | dest_path = ('' if path_to_remote_path(dest_path)=='/' else path_to_remote_path(dest_path)) + '/' + path_to_name(source_file) 164 | # Stamps 165 | print(" ") 166 | print_time() 167 | print_job_binary(source_file,dest_path) 168 | 169 | # upload with SDK. This is the only difference with upload_self(...) 170 | for j in range(0,6): 171 | if j==5: 172 | print_error(note="Trial limit exceeded, skip this file.") 173 | return False 174 | try: 175 | client.item(drive = "me", path = dest_path).upload_async(source_file) 176 | break 177 | except Exception as e: 178 | print_error("Upload",str(e)+", will try again later.") 179 | continue 180 | 181 | # so it's a directory 182 | else: 183 | new_dest_path=dest_path+path_to_name(source_file)+"/" 184 | for new_source_file in os.listdir(source_file): 185 | upload_self_hack(client, source_file+"/"+new_source_file, new_dest_path) 186 | 187 | return True 188 | 189 | 190 | 191 | if __name__ == '__main__': 192 | pass 193 | -------------------------------------------------------------------------------- /onedrivecmd/utils/session.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: Session helper for onedrivecmd 5 | # Created: 09/24/2016 6 | 7 | import onedrivesdk 8 | import logging 9 | import json 10 | from time import time 11 | 12 | try: 13 | from static import * 14 | from helper_file import * 15 | except ImportError: 16 | from .static import * 17 | from .helper_file import * 18 | 19 | ### Session 20 | 21 | def get_access_token(client): 22 | """OneDriveClient->str 23 | 24 | Get the access token that shall be used with all the request that 25 | would require authorization. 26 | 27 | This is just a helper function to assist with self-defined 28 | downloading and uploading. 29 | """ 30 | return str(client.auth_provider.access_token) 31 | 32 | 33 | def refresh_token(client): 34 | """OneDriveClient->OneDriveClient 35 | 36 | Refresh token of the client. 37 | 38 | The default expire time of one token is 3600 secs. 39 | """ 40 | client.auth_provider.refresh_token() 41 | return 42 | 43 | def token_time_to_live(client): 44 | """OneDriveClient->int 45 | 46 | Get the expiration time of token in sec. 47 | 48 | We have to make sure the token is available. 49 | """ 50 | return int(client.auth_provider._session._expires_at - time()) 51 | 52 | ## Make our own even worse Session 53 | 54 | 55 | def save_session(client, path = ''): 56 | """Client, str->None 57 | 58 | Save the current status to a JSON file 59 | 60 | so can be loaded later on to resume the 61 | current status. 62 | 63 | Compared to pickle, 64 | save whether the client is Business or personal account, 65 | and if Business, save its API endpoint 66 | so we can save 1 API call to retrive the endpoint. 67 | 68 | The session JSON file is as important as the user's password. 69 | """ 70 | if client.base_url == 'https://api.onedrive.com/v1.0/': 71 | # Normal 72 | status_dict = { 73 | 'is_business': False, 74 | 'client_id': client.auth_provider._client_id, 75 | 'client.base_url': client.base_url, #'https://api.onedrive.com/v1.0/' 76 | 'client.auth_provider.auth_token_url': client.auth_provider.auth_token_url, #'https://login.live.com/oauth20_token.srf' 77 | 'client.auth_provider.auth_server_url': client.auth_provider.auth_server_url, #'https://login.live.com/oauth20_authorize.srf' 78 | 'client.auth_provider.scopes': client.auth_provider.scopes, 79 | } 80 | status_dict['client.auth_provider._session'] = dict_merge(client.auth_provider._session.__dict__, 81 | {'_expires_at': int(client.auth_provider._session._expires_at), 82 | 'scope_string': ' '.join([str(i) for i in client.auth_provider._session.scope]), 83 | }) 84 | 85 | else: 86 | # Business/office 365 87 | status_dict = { 88 | 'is_business': True, 89 | 'client_id': client.auth_provider._client_id, 90 | 'client.base_url': client.base_url, #'https://{.....}.sharepoint.com/_api/v2.0/' 91 | 'client.auth_provider.auth_token_url': client.auth_provider.auth_token_url, #'https://login.microsoftonline.com/common/oauth2/token' 92 | 'client.auth_provider.auth_server_url': client.auth_provider.auth_server_url[0], #'https://login.microsoftonline.com/common/oauth2/authorize' 93 | 'client.auth_provider.scopes': client.auth_provider.scopes, # empty for business 94 | } 95 | 96 | status_dict['client.auth_provider._session'] = dict_merge(client.auth_provider._session.__dict__, 97 | {'_expires_at': int(client.auth_provider._session._expires_at), 98 | 'scope_string': ' '.join([str(i) for i in client.auth_provider._session.scope]), 99 | }) 100 | 101 | status = json.dumps(status_dict) 102 | 103 | with open(path, "w+") as session_file: 104 | session_file.write(status) 105 | 106 | return 107 | 108 | 109 | def load_session(client, path = ''): 110 | """str->Client 111 | 112 | Load a new client from the saved status file. 113 | """ 114 | ## helper: making a Session from dict we get from session file 115 | # main entrance of function to come after this function 116 | def make_session_from_dict(status_dict): 117 | return onedrivesdk.auth_provider.Session(status_dict['client.auth_provider._session']['token_type'], 118 | status_dict['client.auth_provider._session']['_expires_at'] - time(), 119 | status_dict['client.auth_provider._session']['scope_string'], 120 | status_dict['client.auth_provider._session']['access_token'], 121 | status_dict['client.auth_provider._session']['client_id'], 122 | status_dict['client.auth_provider._session']['auth_server_url'], 123 | status_dict['client.auth_provider._session']['redirect_uri'], 124 | refresh_token=status_dict['client.auth_provider._session']['refresh_token'], 125 | client_secret=status_dict['client.auth_provider._session']['client_secret']) 126 | 127 | ## start of function 128 | ## Read Session file 129 | try: 130 | with open(path, 'r') as session_file: 131 | status_dict = json.loads(session_file.read()) 132 | except IOError as e: 133 | # file not exist or some other problems... 134 | logging.fatal(e.strerror) 135 | logging.fatal('Cannot read the session file!') 136 | exit() #have to die now, or what else can we do? 137 | 138 | ## deterime type of account, run different logics 139 | # Business 140 | if status_dict['is_business']: 141 | # mock http and auth 142 | http_provider = onedrivesdk.HttpProvider() 143 | auth_provider = onedrivesdk.AuthProvider(http_provider, 144 | client_id_business, 145 | auth_server_url=status_dict['client.auth_provider.auth_server_url'], 146 | auth_token_url=status_dict['client.auth_provider.auth_token_url']) 147 | 148 | else: 149 | # personal 150 | http_provider = onedrivesdk.HttpProvider() 151 | auth_provider = onedrivesdk.AuthProvider( 152 | http_provider=http_provider, 153 | client_id=status_dict['client_id'], 154 | scopes=scopes) 155 | 156 | ## inject a Session in 157 | auth_provider._session = make_session_from_dict(status_dict) 158 | 159 | auth_provider.refresh_token() 160 | 161 | ## put API endpoint in 162 | return onedrivesdk.OneDriveClient(status_dict['client.base_url'], auth_provider, http_provider) 163 | 164 | 165 | if __name__=='__main__': 166 | pass 167 | 168 | 169 | ''' 170 | 171 | The old way that save the whole session in a pickle file. 172 | 173 | Replaced by saving more information in JSON 174 | in order to know whether is Business account and its API endpoint. 175 | 176 | # def save_session(client, path = ''): 177 | # """OneDriveClient, str->None 178 | 179 | # Save the session info in a pickle file. 180 | 181 | # Not safe, but whatever. 182 | # """ 183 | # client.auth_provider.save_session(path = path) 184 | # return 185 | 186 | 187 | # def load_session(client, path = ''): 188 | # """str->OneDriveClient 189 | 190 | # Determine whether the session is a normal or Business one, 191 | # load a session from the storaged pickle, 192 | # then refresh so the session is available to use immediately. 193 | # """ 194 | # if not os.path.isfile(path): 195 | # logging.error('Session dump path does not exist') 196 | # raise Exception 197 | 198 | # # look inside the pickle to determine whether is normal or Business 199 | # session_standalone =onedrivesdk.auth_provider.Session.load_session(path = path) 200 | 201 | # if session_standalone.auth_server_url == 'https://login.microsoftonline.com/common/oauth2/token': 202 | # # Business 203 | # http = onedrivesdk.HttpProvider() 204 | # auth = onedrivesdk.AuthProvider(http, 205 | # client_id_business , 206 | # auth_server_url=auth_server_url, 207 | # auth_token_url=auth_token_url) 208 | 209 | # client.auth_provider.load_session(path = path) 210 | 211 | # # refresh token so session good to use immediately 212 | # client.auth_provider.refresh_token() 213 | 214 | # return client 215 | ''' -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | onedrivecmd 2 | ======= 3 | 4 | 5 | 6 | A command line client for Onedrive(including Office 365 and Business). 7 | 8 | Based on [onedrive-sdk-python](https://github.com/OneDrive/onedrive-sdk-python) , with lots of modifications. 9 | 10 | This is very much a copycat of [megacmd](https://github.com/t3rm1n4l/megacmd) , but in different language. 11 | 12 | ### Why onedrivecmd? 13 | Onedrive is a cloud-storage service provided by Microsoft. Education users can get 1TB of storage for free, which can be redeemed at https://products.office.com/en-us/student?tab=students . 14 | 15 | Since the recent update of Onedrive's API, there aren't a lot of *nix softwares that would provide support to Onedrive, most of them are syncing softwares: But I prefer have more control of what I am doing. So here it is, a tiny client that can do the jobs for you. 16 | 17 | ### Features 18 | - Ability to access files and folders using a path URI 19 | - Configuration file (~/.onedrive.json) 20 | - Folder/file get operations, and retry when failed (experimental) 21 | - Folder/file put operations, and retry when failed (experimental) 22 | - List operation (shows file size and timestamp) 23 | - Download and upload with native progress bar (with option of downloading with aria2!) 24 | - Remote download links to your drive(NEW! Not even available via Web console) (Only available at personal due to API limit) 25 | - Supports Office 365! 26 | - Python 2 and 3 compatible. Tested with lots of cases but please report if it is not working somehow. 27 | - Get share link and direct download link! 28 | 29 | ## Install 30 | 31 | As easy as: ```pip install onedrivecmd```! 32 | 33 | Also you can clone this project, then execute ```python3 setup.py install``` or ```python setup.py install``` 34 | 35 | ### Usage 36 | Usage onedrivecmd: 37 | onedrivecmd -h 38 | onedrivecmd [OPTIONS] init 39 | onedrivecmd [OPTIONS] init_business 40 | onedrivecmd [OPTIONS] list od:/foo/bar/ 41 | onedrivecmd [OPTIONS] share od:/foo/doc.txt 42 | onedrivecmd [OPTIONS] direct od:/foo/image.jpg 43 | onedrivecmd [OPTIONS] get od:/foo/file.txt /tmp/ 44 | onedrivecmd [OPTIONS] get od:/boo/dir/ ./localdir/ 45 | onedrivecmd [OPTIONS] put /tmp/hello.txt od:/bar/ 46 | onedrivecmd [OPTIONS] put /tmp/dir/ od:/bar/ 47 | onedrivecmd [OPTIONS] delete od:/foo/bar 48 | onedrivecmd [OPTIONS] mkdir od:/foo/bar/ 49 | onedrivecmd [OPTIONS] search foobar 50 | onedrivecmd [OPTIONS] remote http://thecatapi.com/api/images/get?format=src&type=gif 51 | onedrivecmd [OPTIONS] quota 52 | 53 | 54 | -conf="~/onedrive.json": Config file path, this file is as important as your password! 55 | -h: Help 56 | -hack: Use aria2 to download file, or the SDK's built-in uploader (without progress bar!) 57 | -recursive=false: Recursive listing 58 | -chunk=62914560: Chunk size when uploading 59 | -url=False: Only display the URL when downloading, temp one 60 | 61 | 62 | 63 | ### How to run onedrivecmd? 64 | 65 | #### Install dependencies 66 | 67 | *Only when you are installing from source code* 68 | 69 | There are 3 packages you should install: 70 | 71 | ``` 72 | onedrivesdk < 2 73 | progress 74 | requests 75 | ``` 76 | 77 | Do a ```pip install -r requirements.txt``` at the folder. 78 | 79 | #### Login 80 | 81 | Do a ```onedrivecmd init``` , or ```onedrivecmd init_business``` if you are using Business or Office 365. 82 | 83 | You shall be given a URL like 84 | 85 | ``` 86 | https://login.live.com/oauth20_authorize.srf?scope=wl.signin+wl.offline_access+onedrive.readwrite&redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=aeba6391-92fd-437d-a9d9-33a258b96c4e 87 | ``` 88 | 89 | Authorize your login. 90 | 91 | Yes you shall be redirected to ```https://od.cnbeining.com/```, which apparently is owned by me. This page is hosted at [branch gh-pages](https://github.com/cnbeining/onedrivecmd/blob/gh-pages/index.html), with a Cloudflare at the front. I am doing this so you can just do a quick select-all and paste. If you have doubt, change the information in ```static.py```. 92 | 93 | The login information is storaged at ```~/.onedrive.json```, or any location you demanded. This file should be treated as secret as your password. 94 | 95 | After this very first time init, the ```access_token``` shall be refreshed every time you run the programme. 96 | 97 | 98 | ### Pitfalls 99 | To list directory contents, use: 100 | 101 | $ onedrivecmd list od:/foo/bar/ 102 | 103 | Names ending with '/' is a directory. The size of directory is the size of the sum of its content. 104 | 105 | To recursively list a directory use, -recursive option. 106 | 107 | $ onedrivecmd -recursive list od:/foo/bar/ 108 | 109 | The delete can only move the item to the trash bin, as there is no way of just delete the item. Make sure you clean your trash. 110 | 111 | $ onedrivecmd delete od:/foo/bar/file 112 | 113 | 114 | ### Examples 115 | 116 | $ onedrivecmd init 117 | 118 | https://login.live.com/oauth20_authorize.srf?scope=wl.signin+wl.offline_access+onedrive.readwrite&redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=aeba6391-92fd-437d-a9d9-33a258b96c4e 119 | 120 | Paste this URL into your browser, approve the app's access. 121 | Copy all the code in the new window, and paste it below: 122 | Paste code here: Ma0d6f772-****-e5ea-8d5a-****** 123 | 124 | $ onedrivecmd init_business 125 | ATTENTION: This is for Onedrive Business and Office 365 only. 126 | If you are using normal Onedrive, lease exit and run 127 | 128 | onedrivecmd init 129 | 130 | https://login.microsoftonline.com/common/oauth2/authorize?redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=6fdb55b4-c905-4612-bd23-306c3918217c 131 | 132 | Paste this URL into your browser, approve the app's access. 133 | Copy all the code in the new window, and paste it below: 134 | Paste code here: (Very long!) 135 | 136 | $ onedrivecmd list od:/ 137 | od:/133/ 0 2016-09-24T04:17:58.957000Z 138 | od:/134/ 0 2016-09-24T05:11:17.190000Z 139 | od:/New Folder/ 351 2016-09-22T03:02:25.423000Z 140 | od:/1.png 342677 2016-09-24T04:28:51.617000Z 141 | od:/OneDrive 入门.pdf 1159342 2016-08-23T03:03:55.043000Z 142 | 143 | $ onedrivecmd put /tmp/demo/ od:/test/ 144 | 145 | [2019-03-19 11:57:07] 146 | /tmp/demo/index.html ==> od:/test/demo/index.html 147 | Uploading |################################| 100.0% - 0s 148 | 149 | [2019-03-19 11:57:26] 150 | /tmp/demo/Pic/1.png ==> od:/test/demo/Pic/1.png 151 | Uploading |################################| 100.0% - 0s 152 | 153 | [2019-03-19 11:57:44] 154 | /tmp/demo/Pic/2.png ==> od:/test/demo/Pic/2.png 155 | Uploading |################################| 100.0% - 0s 156 | 157 | [2019-03-19 11:58:03] 158 | /tmp/demo/Pic/test/365.ps1 ==> od:/test/demo/Pic/test/365.ps1 159 | Uploading |################################| 100.0% - 0s 160 | 161 | [2019-03-19 11:58:22] 162 | /tmp/demo/Pic/3.jpg ==> od:/test/demo/Pic/3.jpg 163 | Uploading |################################| 100.0% - 0s 164 | 165 | $ onedrivecmd get od:/1.pdf 166 | Downloading |###### | 21.4% - 74s 167 | 168 | # personal 169 | $ onedrivecmd share od:/1.png 170 | https://1drv.ms/u/s!AnpifX1Elagmb_7sFIiyr2ipY1k 171 | 172 | $ onedrivecmd direct od:/1.png 173 | https://onedrive.live.com/download?resid=26A895447D7D627A!111&authkey=!AP7sFIiyr2ipY1k 174 | 175 | # Office 365 176 | $ onedrivecmd share od:/onedrive.json 177 | https://ad-my.sharepoint.com/personal/email/_layouts/15/guestaccess.aspx?docid=xxx&authkey=xxx 178 | 179 | $ onedrivecmd direct od:/onedrive.json 180 | https://ad-my.sharepoint.com/personal/email/_layouts/15/download.aspx?docid=md5&authkey=xxx 181 | 182 | $ onedrivecmd -hack get od:/1.png 183 | [#e257f9 16KiB/334KiB(4%) CN:1 DL:230KiB ETA:1s] 184 | 09/24 02:10:56 [NOTICE] Download complete: **onedrivecmd/1.png 185 | 186 | Download Results: 187 | gid |stat|avg speed |path/URI 188 | ======+====+===========+======================================================= 189 | e257f9|OK | 343KiB/s|**onedrivecmd/1.png 190 | 191 | Status Legend: 192 | (OK):download completed. 193 | 194 | $ onedrivecmd search file.txt 195 | 01DERSD4MVUNK66BVQRFFZZEDK7FILJSYS file.txt 1073741824 2017-08-30T05:55:24Z 196 | 01DERSD4JFGCT7P2VFFVEI3KXDPASSCX2H files.txt 89 2017-08-30T05:46:38Z 197 | 198 | $ onedrivecmd mkdir od:/145 199 | 200 | $ onedrivecmd remote "http://wscont2.apps.microsoft.com/winstore/1x/.../Screenshot.225037.100000.jpg" 201 | https://api.onedrive.com/v1.0/monitor/... 202 | 203 | $ onedrivecmd quota 204 | 205 | Total Size: 1.0TiB, 206 | Used: 1.6MiB, 207 | Remaining: 1024.0GiB, 208 | Deleted: 0.0B, 209 | 210 | Your state is: normal 211 | 212 | ### TODO 213 | 214 | * Recursive 'mkdir'. 215 | * Perfect retry-when-failed function. 216 | * Move 217 | * Code refactoring 218 | * I will not write sync since we have [rclone](https://github.com/ncw/rclone) which already supports Onedrive. Feel free to send me pull requests though. 219 | * I cannot think of anything. Open issues if you have amazing ideas. 220 | 221 | ### How to Contribute ? 222 | 223 | Any PR or issue would be appreciated. 224 | 225 | ### License 226 | 227 | AGPL 228 | 229 | ### Author 230 | 231 | Beining, https://www.cnbeining.com/ , ```i [at] cnbeining.com``` . 232 | 233 | Driven by coffee, coffee and coffee. 234 | 235 | 236 | Collaborator/Dict Xiong, https://beardic.cn/, ```me [at] beardic.cn```. 237 | 238 | Furkan ÖZOĞUL (https://gitlab.com/ozogulf ) solved the SDK issue. 239 | 240 | 241 | ### 中文说明 242 | 243 | [点这里](https://github.com/cnbeining/onedrivecmd/wiki/%E4%B8%AD%E6%96%87%E8%AF%B4%E6%98%8E) 244 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | onedrivecmd 2 | =========== 3 | 4 | A command line client for Onedrive(including Office 365 and Business). 5 | 6 | Based on 7 | `onedrive-sdk-python `__ 8 | , with lots of modifications. 9 | 10 | This is very much a copycat of 11 | `megacmd `__ , but in different 12 | language. 13 | 14 | Why onedrivecmd? 15 | ~~~~~~~~~~~~~~~~ 16 | 17 | Onedrive is a cloud-storage service provided by Microsoft. Education 18 | users can get 1TB of storage for free, which can be redeemed at 19 | https://products.office.com/en-us/student?tab=students . 20 | 21 | Since the recent update of Onedrive’s API, there aren’t a lot of \*nix 22 | softwares that would provide support to Onedrive, most of them are 23 | syncing softwares: But I prefer have more control of what I am doing. So 24 | here it is, a tiny client that can do the jobs for you. 25 | 26 | Features 27 | ~~~~~~~~ 28 | 29 | - Ability to access files and folders using a path URI 30 | - Configuration file (~/.onedrive.json) 31 | - Folder/file get operations, and retry when failed (experimental) 32 | - Folder/file put operations, and retry when failed (experimental) 33 | - List operation (shows file size and timestamp) 34 | - Download and upload with native progress bar (with option of 35 | downloading with aria2!) 36 | - Remote download links to your drive(NEW! Not even available via Web 37 | console) (Only available at personal due to API limit) 38 | - Supports Office 365! 39 | - Python 2 and 3 compatible. Tested with lots of cases but please 40 | report if it is not working somehow. 41 | - Get share link and direct download link! 42 | 43 | Install 44 | ------- 45 | 46 | As easy as: ``pip install onedrivecmd``! 47 | 48 | Also you can clone this project, then execute 49 | ``python3 setup.py install`` or ``python setup.py install`` 50 | 51 | Usage 52 | ~~~~~ 53 | 54 | :: 55 | 56 | Usage onedrivecmd: 57 | onedrivecmd -h 58 | onedrivecmd [OPTIONS] init 59 | onedrivecmd [OPTIONS] init_business 60 | onedrivecmd [OPTIONS] list od:/foo/bar/ 61 | onedrivecmd [OPTIONS] share od:/foo/doc.txt 62 | onedrivecmd [OPTIONS] direct od:/foo/image.jpg 63 | onedrivecmd [OPTIONS] get od:/foo/file.txt /tmp/ 64 | onedrivecmd [OPTIONS] get od:/boo/dir/ ./localdir/ 65 | onedrivecmd [OPTIONS] put /tmp/hello.txt od:/bar/ 66 | onedrivecmd [OPTIONS] put /tmp/dir/ od:/bar/ 67 | onedrivecmd [OPTIONS] delete od:/foo/bar 68 | onedrivecmd [OPTIONS] mkdir od:/foo/bar/ 69 | onedrivecmd [OPTIONS] search foobar 70 | onedrivecmd [OPTIONS] remote http://thecatapi.com/api/images/get?format=src&type=gif 71 | onedrivecmd [OPTIONS] quota 72 | 73 | 74 | -conf="~/onedrive.json": Config file path, this file is as important as your password! 75 | -h: Help 76 | -hack: Use aria2 to download file, or the SDK's built-in uploader (without progress bar!) 77 | -recursive=false: Recursive listing 78 | -chunk=62914560: Chunk size when uploading 79 | -url=False: Only display the URL when downloading, temp one 80 | 81 | How to run onedrivecmd? 82 | ~~~~~~~~~~~~~~~~~~~~~~~ 83 | 84 | Install dependencies: 85 | 86 | 87 | *Only when you are installing from source code* 88 | 89 | There are 3 packages you should install: 90 | 91 | :: 92 | 93 | onedrivesdk < 2 94 | progress 95 | requests 96 | 97 | Do a ``pip install -r requirements.txt`` at the folder. 98 | 99 | Login: 100 | 101 | Do a ``onedrivecmd init`` , or ``onedrivecmd init_business`` if you are 102 | using Business or Office 365. 103 | 104 | You shall be given a URL like 105 | 106 | :: 107 | 108 | https://login.live.com/oauth20_authorize.srf?scope=wl.signin+wl.offline_access+onedrive.readwrite&redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=aeba6391-92fd-437d-a9d9-33a258b96c4e 109 | 110 | Authorize your login. 111 | 112 | Yes you shall be redirected to ``https://od.cnbeining.com/``, which 113 | apparently is owned by me. This page is hosted at `branch 114 | gh-pages `__, 115 | with a Cloudflare at the front. I am doing this so you can just do a 116 | quick select-all and paste. If you have doubt, change the information in 117 | ``static.py``. 118 | 119 | The login information is storaged at ``~/.onedrive.json``, or any 120 | location you demanded. This file should be treated as secret as your 121 | password. 122 | 123 | After this very first time init, the ``access_token`` shall be refreshed 124 | every time you run the programme. 125 | 126 | Pitfalls 127 | ~~~~~~~~ 128 | 129 | To list directory contents, use: 130 | 131 | :: 132 | 133 | $ onedrivecmd list od:/foo/bar/ 134 | 135 | Names ending with ‘/’ is a directory. The size of directory is the size 136 | of the sum of its content. 137 | 138 | To recursively list a directory use, -recursive option. 139 | 140 | :: 141 | 142 | $ onedrivecmd -recursive list od:/foo/bar/ 143 | 144 | The delete can only move the item to the trash bin, as there is no way 145 | of just delete the item. Make sure you clean your trash. 146 | 147 | :: 148 | 149 | $ onedrivecmd delete od:/foo/bar/file 150 | 151 | Examples 152 | ~~~~~~~~ 153 | 154 | :: 155 | 156 | $ onedrivecmd init 157 | 158 | https://login.live.com/oauth20_authorize.srf?scope=wl.signin+wl.offline_access+onedrive.readwrite&redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=aeba6391-92fd-437d-a9d9-33a258b96c4e 159 | 160 | Paste this URL into your browser, approve the app's access. 161 | Copy all the code in the new window, and paste it below: 162 | Paste code here: Ma0d6f772-****-e5ea-8d5a-****** 163 | 164 | $ onedrivecmd init_business 165 | ATTENTION: This is for Onedrive Business and Office 365 only. 166 | If you are using normal Onedrive, lease exit and run 167 | 168 | onedrivecmd init 169 | 170 | https://login.microsoftonline.com/common/oauth2/authorize?redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=6fdb55b4-c905-4612-bd23-306c3918217c 171 | 172 | Paste this URL into your browser, approve the app's access. 173 | Copy all the code in the new window, and paste it below: 174 | Paste code here: (Very long!) 175 | 176 | $ onedrivecmd list od:/ 177 | od:/133/ 0 2016-09-24T04:17:58.957000Z 178 | od:/134/ 0 2016-09-24T05:11:17.190000Z 179 | od:/New Folder/ 351 2016-09-22T03:02:25.423000Z 180 | od:/1.png 342677 2016-09-24T04:28:51.617000Z 181 | od:/OneDrive 入门.pdf 1159342 2016-08-23T03:03:55.043000Z 182 | 183 | $ onedrivecmd put /tmp/demo/ od:/test/ 184 | 185 | [2019-03-19 11:57:07] 186 | /tmp/demo/index.html ==> od:/test/demo/index.html 187 | Uploading |################################| 100.0% - 0s 188 | 189 | [2019-03-19 11:57:26] 190 | /tmp/demo/Pic/1.png ==> od:/test/demo/Pic/1.png 191 | Uploading |################################| 100.0% - 0s 192 | 193 | [2019-03-19 11:57:44] 194 | /tmp/demo/Pic/2.png ==> od:/test/demo/Pic/2.png 195 | Uploading |################################| 100.0% - 0s 196 | 197 | [2019-03-19 11:58:03] 198 | /tmp/demo/Pic/test/365.ps1 ==> od:/test/demo/Pic/test/365.ps1 199 | Uploading |################################| 100.0% - 0s 200 | 201 | [2019-03-19 11:58:22] 202 | /tmp/demo/Pic/3.jpg ==> od:/test/demo/Pic/3.jpg 203 | Uploading |################################| 100.0% - 0s 204 | 205 | $ onedrivecmd get od:/1.pdf 206 | Downloading |###### | 21.4% - 74s 207 | 208 | # personal 209 | $ onedrivecmd share od:/1.png 210 | https://1drv.ms/u/s!AnpifX1Elagmb_7sFIiyr2ipY1k 211 | 212 | $ onedrivecmd direct od:/1.png 213 | https://onedrive.live.com/download?resid=26A895447D7D627A!111&authkey=!AP7sFIiyr2ipY1k 214 | 215 | # Office 365 216 | $ onedrivecmd share od:/onedrive.json 217 | https://ad-my.sharepoint.com/personal/email/_layouts/15/guestaccess.aspx?docid=xxx&authkey=xxx 218 | 219 | $ onedrivecmd direct od:/onedrive.json 220 | https://ad-my.sharepoint.com/personal/email/_layouts/15/download.aspx?docid=md5&authkey=xxx 221 | 222 | $ onedrivecmd -hack get od:/1.png 223 | [#e257f9 16KiB/334KiB(4%) CN:1 DL:230KiB ETA:1s] 224 | 09/24 02:10:56 [NOTICE] Download complete: **onedrivecmd/1.png 225 | 226 | Download Results: 227 | gid |stat|avg speed |path/URI 228 | ======+====+===========+======================================================= 229 | e257f9|OK | 343KiB/s|**onedrivecmd/1.png 230 | 231 | Status Legend: 232 | (OK):download completed. 233 | 234 | $ onedrivecmd search file.txt 235 | 01DERSD4MVUNK66BVQRFFZZEDK7FILJSYS file.txt 1073741824 2017-08-30T05:55:24Z 236 | 01DERSD4JFGCT7P2VFFVEI3KXDPASSCX2H files.txt 89 2017-08-30T05:46:38Z 237 | 238 | $ onedrivecmd mkdir od:/145 239 | 240 | $ onedrivecmd remote "http://wscont2.apps.microsoft.com/winstore/1x/.../Screenshot.225037.100000.jpg" 241 | https://api.onedrive.com/v1.0/monitor/... 242 | 243 | $ onedrivecmd quota 244 | 245 | Total Size: 1.0TiB, 246 | Used: 1.6MiB, 247 | Remaining: 1024.0GiB, 248 | Deleted: 0.0B, 249 | 250 | Your state is: normal 251 | 252 | TODO 253 | ~~~~ 254 | 255 | - Recursive ‘mkdir’. 256 | - Perfect retry-when-failed function. 257 | - Move 258 | - Code refactoring 259 | - I will not write sync since we have 260 | `rclone `__ which already supports 261 | Onedrive. Feel free to send me pull requests though. 262 | - I cannot think of anything. Open issues if you have amazing ideas. 263 | 264 | How to Contribute ? 265 | ~~~~~~~~~~~~~~~~~~~ 266 | 267 | Any PR or issue would be appreciated. 268 | 269 | License 270 | ~~~~~~~ 271 | 272 | AGPL 273 | 274 | Author 275 | ~~~~~~ 276 | 277 | Beining, https://www.cnbeining.com/ , ``i [at] cnbeining.com`` . 278 | 279 | Driven by coffee, coffee and coffee. 280 | 281 | Collaborator/Dict Xiong, https://beardic.cn/, ``me [at] beardic.cn``. 282 | 283 | Furkan ÖZOĞUL (https://gitlab.com/ozogulf ) solved the SDK issue. 284 | 285 | 中文说明 286 | ~~~~~~~~ 287 | 288 | `点这里 `__ 289 | -------------------------------------------------------------------------------- /onedrivecmd/utils/actions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding:utf-8 3 | # Author: Beining -- 4 | # Purpose: Actions of onedrivecmd 5 | # Created: 09/24/2016 6 | 7 | from __future__ import unicode_literals 8 | from collections import OrderedDict 9 | 10 | try: 11 | from static import * 12 | from uploader import * 13 | from helper_file import * 14 | from helper_item import * 15 | from session import * 16 | from helper_print import * 17 | from downloader import * 18 | except ImportError: 19 | from .static import * 20 | from .uploader import * 21 | from .helper_file import * 22 | from .helper_item import * 23 | from .session import * 24 | from .helper_print import * 25 | from .downloader import * 26 | 27 | try: 28 | from urlparse import urlparse # python 2 29 | except: 30 | from urllib.parse import urlparse 31 | 32 | import onedrivesdk 33 | from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest 34 | from os.path import splitext 35 | 36 | ### Action 37 | 38 | ##Init 39 | def init_business(client): 40 | """onedrivesdk.request.one_drive_client.OneDriveClient->onedrivesdk.request.one_drive_client.OneDriveClient 41 | 42 | Important: Only used for Business/Office 365! 43 | 44 | Init of the script. 45 | 46 | Let user login, get the details, save the details in a conf file. 47 | 48 | Used at the first time login. 49 | 50 | Ref: 51 | https://github.com/OneDrive/onedrive-sdk-python#onedrive-for-business 52 | https://dev.onedrive.com/auth/aad_oauth.htm#register-your-app-with-azure-active-directory 53 | """ 54 | # auth url: 55 | # https://login.microsoftonline.com/common/oauth2/authorize?scope=wl.signin+wl.offline_access+onedrive.readwrite&redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=bac72a8b-77c8-4b76-8b8f-b7c65a239ce6 56 | 57 | http = onedrivesdk.HttpProvider() 58 | auth = onedrivesdk.AuthProvider(http, 59 | client_id_business, 60 | auth_server_url = auth_server_url, 61 | auth_token_url = auth_token_url) 62 | auth_url = auth.get_auth_url(redirect_uri) 63 | 64 | # now the url looks like "('https://login.microsoftonline.com/common/oauth2/authorize',)?redirect_uri=https%3A%2F%2Fod.cnbeining.com&response_type=code&client_id=bac72a8b-77c8-4b76-8b8f-b7c65a239ce6" 65 | 66 | try: # Python 2 67 | auth_url = auth_url.encode('utf-8').replace("('", '').replace("',)", '') 68 | except TypeError: 69 | auth_url = auth_url.replace("('", '').replace("',)", '') 70 | 71 | # Ask for the code 72 | print('ATTENTION: This is for Onedrive Business and Office 365 only.') 73 | print('If you are using normal Onedrive, lease exit and run') 74 | print('') 75 | print('onedrivecmd init') 76 | print('') 77 | print(auth_url) 78 | print('') 79 | print('Paste this URL into your browser, approve the app\'s access.') 80 | print('Copy all the code in the new window, and paste it below:') 81 | 82 | code = input('Paste code here: ') 83 | 84 | auth.authenticate(code, redirect_uri, client_secret_business, resource = 'https://api.office.com/discovery/') 85 | 86 | # this step is slow 87 | service_info = ResourceDiscoveryRequest().get_service_info(auth.access_token)[0] 88 | 89 | auth.redeem_refresh_token(service_info.service_resource_id) 90 | 91 | client = onedrivesdk.OneDriveClient(service_info.service_resource_id + '_api/v2.0/', auth, http) 92 | 93 | # print(client) 94 | 95 | return client 96 | 97 | 98 | def init_normal(client): 99 | """onedrivesdk.request.one_drive_client.OneDriveClient->onedrivesdk.request.one_drive_client.OneDriveClient 100 | 101 | Important: Used for normal Onedrive account, NOT office 365! 102 | 103 | Init of the script. 104 | 105 | Let user login, get the details, save the details in a conf file. 106 | 107 | Used at the first time login. 108 | """ 109 | 110 | http_provider = onedrivesdk.HttpProvider() 111 | auth_provider = onedrivesdk.AuthProvider( 112 | http_provider = http_provider, 113 | client_id = client_id_normal, 114 | scopes = scopes) 115 | 116 | client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider) 117 | 118 | auth_url = client.auth_provider.get_auth_url(redirect_uri) 119 | 120 | # Ask for the code 121 | print('ATTENTION: This is for normal Onedrive only.') 122 | print('If you are using Onedrive Business and Office 365,') 123 | print('Please exit and run') 124 | print('') 125 | print('onedrivecmd init_business') 126 | print('') 127 | print(auth_url) 128 | print('') 129 | print('Paste this URL into your browser, approve the app\'s access.') 130 | print('Copy all the code in the new window, and paste it below:') 131 | 132 | code = input('Paste code here: ') 133 | 134 | client.auth_provider.authenticate(code, redirect_uri, client_secret_normal) 135 | 136 | return client 137 | 138 | 139 | def do_init(client, args): 140 | """onedrivesdk.request.one_drive_client.OneDriveClient, args->onedrivesdk.request.one_drive_client.OneDriveClient 141 | 142 | Init of the script. 143 | 144 | Let user login, get the details 145 | 146 | Used at the first time login. 147 | """ 148 | if args.mode == 'init_business': 149 | client = init_business(client) 150 | else: 151 | client = init_normal(client) 152 | 153 | return client 154 | 155 | 156 | ## Others 157 | def do_get(client, args): 158 | """OneDriveClient, [str] -> OneDriveClient 159 | 160 | Get a remote files information, 161 | then get the temp download link that is only vaild for a couple of minutes, 162 | download it with a homebrew single-thread downloader with progress bar, 163 | or call aria2 to do the download. 164 | """ 165 | if not args.rest[-1].startswith('od:/'): 166 | local_dir=args.rest[-1] 167 | if local_dir.endswith("/") and local_dir != "/": 168 | local_dir=local_dir[:-1] 169 | args.rest=args.rest[:-1] 170 | else: 171 | local_dir='.' 172 | 173 | for f in args.rest: 174 | if not f.startswith("od:/"): 175 | continue 176 | download_self(client=client, 177 | remote_path=f, 178 | local_dir=local_dir, 179 | url=args.url, 180 | hack=args.hack) 181 | return client 182 | 183 | 184 | def do_share(client, args): 185 | """OneDriveClient, [str] -> OneDriveClient 186 | 187 | Get a remote file/folder's information, 188 | then create share link of such item, 189 | and print it. 190 | 191 | Supposedly this is a permanent link. 192 | """ 193 | 194 | for f in args.rest: 195 | 196 | # get a file item 197 | item = get_remote_item(client, path = f) 198 | 199 | # some error handling 200 | if item is None: 201 | print_error("Remote file", "File {path} does not exist!".format(path = f)) 202 | #logging.warning('File {path} do not exist!'.format(path = f)) 203 | return None 204 | 205 | permission = client.item(id = item.id).create_link("view").post() 206 | 207 | print(permission.link.web_url.replace('15/guestaccess.aspx', '15/download.aspx')) 208 | 209 | return client 210 | 211 | 212 | def do_direct(client, args): 213 | """OneDriveClient, [str] -> OneDriveClient 214 | 215 | Get a remote file/folder's information, 216 | then create share link of such item, 217 | convert the link to direct link, 218 | and print it. 219 | 220 | Supposedly this is a permanent link. Could use another 301 to final link. 221 | """ 222 | 223 | for f in args.rest: 224 | 225 | # get a file item 226 | item = get_remote_item(client, path = f) 227 | 228 | # some error handling 229 | if item is None: 230 | print_error("Remote file", "File {path} does not exist!".format(path = f)) 231 | break 232 | 233 | permission = client.item(id = item.id).create_link("view").post() 234 | 235 | if 'sharepoint.com' in permission.link.web_url: # office 365 236 | # link like: 237 | # https://xxx-my.sharepoint.com/:b:/g/personal/xx_xxx_onmicrosoft_com/blah-blah 238 | parsed_uri = urlparse(permission.link.web_url) 239 | domain = '{uri.scheme}://{uri.netloc}/'.format(uri = parsed_uri) #https://xxx-my.sharepoint.com/ 240 | resid = str(parsed_uri.path.split('/')[-1]) # blah-blah 241 | user_info = str(parsed_uri.path.split('personal/')[1].split('/')[0]) # xxx_xxxxxx_onmicrosoft_com 242 | 243 | # Use the original file extension for the URL 244 | extention = str(splitext(item.name)[1]) 245 | 246 | direct_link = domain + 'personal/' + user_info + '/_layouts/15/download.aspx?share=' + resid 247 | if len(extention[1]) > 0: 248 | direct_link += '&ext=' + extention 249 | 250 | print(direct_link) 251 | 252 | 253 | if '1drv.ms' in permission.link.web_url: # personal 254 | # link like: https://1drv.ms/u/s!blahblah 255 | req = requests.get(permission.link.web_url, allow_redirects = False) 256 | if req.status_code > 201: 257 | print_error("Request", str(req.status_code)+" "+req.json()['error']['message']) 258 | return None 259 | # link become: https://onedrive.live.com/redir?resid=xxx!111&authkey=!xxx 260 | print(req.headers['Location'].replace('redir?', 'download?')) 261 | 262 | return client 263 | 264 | 265 | def do_list(client, args, lFolders = None): 266 | """OneDriveClient, [str], str -> OneDriveClient 267 | 268 | List the content of a remote folder, 269 | with possbility of doing a recurrsive listing. 270 | 271 | If the user is using both flag recurrsive and multiple targets, 272 | or listing a huge drive at its root folder, 273 | the programme can just...crash. But who cares? I do not own Microsoft. 274 | """ 275 | 276 | is_recursive = args.recursive 277 | show_fullpath = args.fullpath 278 | 279 | # recursive call 280 | if isinstance(lFolders, list): 281 | folder_list = lFolders 282 | else: # first call 283 | folder_list = args.rest 284 | 285 | # Nothing provided. Instead of giving a error, list the root folder 286 | if folder_list == []: 287 | folder_list.append('/') 288 | 289 | for path in folder_list: 290 | # get the folder entry point 291 | curPath=path 292 | if not curPath.endswith("/"): 293 | curPath=curPath+"/" 294 | folder = get_remote_item(client, path = curPath) 295 | 296 | if not folder.folder: 297 | print_error("Remote item", curPath+" is not a folder!") 298 | return client 299 | else: 300 | folder=get_remote_folder_children(client, id=folder.id) 301 | 302 | for i in folder: 303 | if show_fullpath: 304 | name = 'od:' + curPath + '/' + i.name 305 | else: 306 | # if name start with 'od:/', users may think it was in the root directory '/' 307 | name = 'od:' + i.name 308 | 309 | if i.folder: 310 | # make a little difference so the user can notice 311 | name += '/' 312 | 313 | # handle recursive 314 | if is_recursive: 315 | do_list(client, args, [curPath + i.name + '/']) 316 | 317 | # format as megacmd 318 | 319 | # for some machines a time data does not not match error will be raised 320 | # for whatever reason so I just put a whatever patch here 321 | try: 322 | created_date_time = i.created_date_time.strftime(i.DATETIME_FORMAT) 323 | except ValueError as e: 324 | created_date_time = i._prop_dict["createdDateTime"] 325 | 326 | print('{name}\t{size}\t{created_date_time}'.format(name = name, 327 | size = i.size, 328 | created_date_time = created_date_time)) 329 | 330 | return client 331 | 332 | 333 | def do_put(client, args): 334 | """OneDriveClient, [str] -> OneDriveClient 335 | 336 | Put local item(s) to a remote FOLDER. 337 | 338 | If no remote dir is specfied, will upload to root dir. 339 | 340 | A home brew uploading option is provided to show progress bar 341 | and manually adjust chunk size. 342 | 343 | The chunk size should be times of 320KiB, or shoot could happen: 344 | https://dev.onedrive.com/items/upload_large_files.htm#best-practices 345 | """ 346 | # set target dir 347 | if not args.rest[-1].startswith('od:/'): 348 | from_list = args.rest 349 | target_dir = 'od:/' 350 | 351 | else: 352 | from_list = args.rest[:-1] 353 | target_dir = args.rest[-1] 354 | 355 | # fix python cannot split path without / at end 356 | if not target_dir.endswith('/'): 357 | target_dir += '/' 358 | 359 | for i in from_list: 360 | # SDK one 361 | # ONLY USED WITH HACK 362 | if args.hack: 363 | upload_self_hack(client=client, 364 | source_file = i, 365 | dest_path = target_dir) 366 | #client.item(drive = "me", path = target_dir[3:-1]).upload_async(i) 367 | 368 | # Home brew one, with progress bar 369 | else: 370 | upload_self(client = client, 371 | source_file = i, 372 | dest_path = target_dir, 373 | chunksize = int(args.chunk)) 374 | 375 | return client 376 | 377 | 378 | def do_delete(client, args): 379 | """OneDriveClient, [str] -> OneDriveClient 380 | 381 | Move an item into trash bin. 382 | 383 | The folder must be empty before being deleted. 384 | 385 | There is currently NO WAY of permanently deleting an item via API/SDK. 386 | 387 | Somehow the SDK does not have this function. 388 | """ 389 | for i in args.rest: 390 | if i.startswith('od:/'): # is somewhere remote 391 | f = get_remote_item(client, path = i) 392 | 393 | # make the request, we have to do it ourselves 394 | req = requests.delete(client.base_url + '/drive/items/{id}'.format(id = f.id), 395 | headers = {'Authorization': 'bearer {access_token}'.format( 396 | access_token = get_access_token(client)), }) 397 | if req.status_code != 204: 398 | print_error("Request", str(req.status_code)+" "+req.json()['error']['message']) 399 | return None 400 | 401 | return client 402 | 403 | 404 | def do_mkdir(client, args): 405 | """OneDriveClient, [str] -> OneDriveClient 406 | 407 | Make a remote folder. 408 | 409 | This is NOT a recursive one: the father folder must exist. 410 | 411 | The SDK somehow refuse to work. Have to use API. 412 | """ 413 | for folder_path in args.rest: 414 | if folder_path.startswith('od:'): 415 | folder_path = folder_path[3:] 416 | 417 | # make sure we are making the right folder 418 | if folder_path.endswith('/'): 419 | folder_path = folder_path[:-1] 420 | 421 | parent_path = os.path.dirname(folder_path) 422 | 423 | req = requests.get(client.base_url + '/drive/root:{parent_path}'.format(parent_path = parent_path), 424 | headers = {'Authorization': 'bearer {access_token}'.format( 425 | access_token = get_access_token(client)), 426 | 'Content-Type': 'application/json', 427 | 'Prefer': 'respond-async', }) 428 | 429 | if req.status_code > 201: 430 | print_error("Request",str(req.status_code)+" "+req.json()['error']['message']) 431 | return None 432 | 433 | req = convert_utf8_dict_to_dict(req.json()) 434 | parent_id = req['id'] 435 | 436 | data = OrderedDict([ 437 | ("name", path_to_name(folder_path)), 438 | ("folder", {}) 439 | ]) 440 | 441 | req = requests.post(client.base_url + '/drive/items/{parent_id}/children'.format(parent_id = parent_id), 442 | headers = {'Authorization': 'bearer {access_token}'.format( 443 | access_token = get_access_token(client)), 444 | 'Content-Type': 'application/json', 445 | 'Prefer': 'respond-async', }, 446 | json = data) 447 | 448 | if req.status_code > 201: 449 | print("\033[31mRequest error:\033[0m "+req.json()['error']['message']) 450 | return None 451 | 452 | req = convert_utf8_dict_to_dict(req.json()) 453 | 454 | if not req['name']: 455 | print_error("Remote file", "Cannot create {folder_path}".format(folder_path = folder_path)) 456 | return None 457 | 458 | return client 459 | 460 | 461 | def do_move(client, args): 462 | """OneDriveClient, [str] -> OneDriveClient 463 | 464 | Move a remote item to a remote location. 465 | 466 | Also can be used to rename. 467 | 468 | Not working so well.... 469 | """ 470 | from_location = args.rest[0] 471 | to_location = args.rest[1] 472 | 473 | # rename 474 | if path_to_remote_path(from_location) == path_to_remote_path(to_location): 475 | renamed_item = onedrivesdk.Item() 476 | renamed_item.name = path_to_name(to_location) 477 | 478 | get_bare_item_by_path(client, from_location).update(renamed_item) 479 | return client 480 | 481 | # real move 482 | moved_item = onedrivesdk.Item() 483 | to_item = get_bare_item_by_path(client, to_location) 484 | 485 | # if target is folder, put the item under 486 | if to_item.folder: 487 | moved_item.parent_reference = to_item 488 | get_bare_item_by_path(client, from_location).update(renamed_item) 489 | 490 | 491 | def do_remote(client, args): 492 | """OneDriveClient, [str] -> OneDriveClient 493 | 494 | Do a remote upload to the Drive. 495 | 496 | A link will be shown to get the current state of uploading. 497 | 498 | This is ONLY vaild for PERSONAL! 499 | 500 | args.rest: list of remote URLs. 501 | """ 502 | for i in args.rest: 503 | # There is no guarantee that this shall be normal, JUST like 504 | # all the similar services 505 | json_data = OrderedDict([('@content.sourceUrl', i), ('file', {}), ('name', path_to_name(i))]) 506 | 507 | root = client.item(drive = 'me', id = 'root').get() 508 | parent_id = root.id 509 | 510 | req = requests.post(client.base_url + 'drive/items/{parent_id}/children'.format(parent_id = parent_id), 511 | data = json.dumps(json_data), 512 | headers = {'Authorization': 'bearer {access_token}'.format( 513 | access_token = get_access_token(client)), 514 | 'Content-Type': 'application/json', 515 | 'Prefer': 'respond-async', }) 516 | if req.status_code > 201: 517 | print_error("Request", str(req.status_code)+" "+req.json()['error']['message']) 518 | return None 519 | print(req.headers['location']) 520 | 521 | return client 522 | 523 | 524 | def do_quota(client, args): 525 | """OneDriveClient, [str] -> OneDriveClient 526 | 527 | Check the quota of the drive and print the data. 528 | 529 | A link will be shown to get the current state of uploading. 530 | 531 | Details of the states: 532 | https://dev.onedrive.com/facets/quotainfo_facet.htm 533 | 534 | WARNING: 535 | At least for Business account, 536 | "used" is not returned, UNLIKE stated in the documentation! 537 | """ 538 | req = requests.get(client.base_url + 'drive/', 539 | headers = { 540 | 'Authorization': 'bearer {access_token}'.format(access_token = get_access_token(client)), 541 | 'content-type': 'application/json'}) 542 | if req.status_code > 201: 543 | print_error("Request", str(req.status_code)+" "+req.json()['error']['message']) 544 | return None 545 | print(''' 546 | Total Size: {total}, 547 | Used: {used}, 548 | Remaining: {remaining}, 549 | Deleted: {deleted}, 550 | 551 | Your state is: {state} 552 | '''.format(total = sizeof_fmt(req.json()['quota']['total']), 553 | used = sizeof_fmt(req.json()['quota']['total'] - req.json()['quota']['remaining']), 554 | remaining = sizeof_fmt(req.json()['quota']['remaining']), 555 | deleted = sizeof_fmt(req.json()['quota']['deleted']), 556 | state = req.json()['quota']['state'] 557 | ) 558 | ) 559 | 560 | return client 561 | 562 | 563 | def do_search(client, args): 564 | """OneDriveClient, [str] -> OneDriveClient 565 | 566 | Search the drive and get list of files. 567 | 568 | A link will be shown to get the current state of uploading. 569 | 570 | Details of the states: 571 | https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_search 572 | """ 573 | 574 | 575 | 576 | # reuse session for faster multi page query 577 | requests_session = requests.Session() 578 | 579 | search_query = ' '.join(args.rest) 580 | 581 | search_url = client.base_url + "drive//root/search(q='{search_query}')".format(search_query = search_query) 582 | 583 | access_token = get_access_token(client) 584 | 585 | item_list = get_search_item_list_single_page_by_url_rec(requests_session, access_token, search_url, item_list = []) 586 | 587 | for item in item_list: 588 | print('{id}\t{name}\t{size}\t{created_date_time}'.format(id = item['id'], 589 | name = item['name'], 590 | size = item['size'], 591 | created_date_time = item['lastModifiedDateTime'] 592 | )) 593 | 594 | return client 595 | 596 | 597 | if __name__ == '__main__': 598 | pass 599 | 600 | """ 601 | The old do_get 602 | 603 | # if directly download, use the build in download() method 604 | # this method does not have any verbose so good luck with your 605 | # life downloading large files. 606 | # It would not be so miserble since OneDrive solely support filesize 607 | # as huge as 10GiB, and 2GiB for Business accounts. Yay! 608 | logging.info('Downloading {local_name}'.format(local_name = local_name)) 609 | client.item(drive='me', id=item.id).download('./' + local_name) 610 | """ 611 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------