Example #1
0
    def test_method_collections(self, MockHttpProvider, MockAuthProvider):
        """
        Test that collections are returned properly from method calls that return collections
        """
        response = HttpResponse(
            200, None,
            json.dumps({
                "@odata.nextLink":
                "testing",
                "value": [{
                    "name": "test1",
                    "folder": {}
                }, {
                    "name": "test2"
                }]
            }))

        instance = MockHttpProvider.return_value
        instance.send.return_value = response

        instance = MockAuthProvider.return_value
        instance.authenticate.return_value = "blah"
        instance.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl", http_provider,
                                            auth_provider)

        items = client.drives["me"].items["testitem!id"].delta().request().get(
        )
        request = onedrivesdk.ItemDeltaRequest.get_next_page_request(
            items, client, None)
        assert type(request) is ItemDeltaRequest
        assert type(request.get()) is ItemDeltaCollectionPage
Example #2
0
    def bauthenticator(self):
        from onedrivesdk.helpers.resource_discovery import ResourceDiscoveryRequest

        discovery_uri = 'https://api.office.com/discovery/'
        auth_server_url = 'https://login.microsoftonline.com/common/oauth2/authorize'
        auth_token_url = 'https://login.microsoftonline.com/common/oauth2/token'

        http = onedrivesdk.HttpProvider()
        auth = onedrivesdk.AuthProvider(http,
                                        self.client_id,
                                        auth_server_url=auth_server_url,
                                        auth_token_url=auth_token_url)
        auth_url = auth.get_auth_url(redirect_uri)
        code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
        auth.authenticate(code,
                          redirect_uri,
                          self.client_secret,
                          resource=discovery_uri)
        # If you have access to more than one service, you'll need to decide
        # which ServiceInfo to use instead of just using the first one, as below.
        service_info = ResourceDiscoveryRequest().get_service_info(
            auth.access_token)[0]
        auth.redeem_refresh_token(service_info.service_resource_id)
        client = onedrivesdk.OneDriveClient(
            service_info.service_resource_id + '/_api/v2.0/', auth, http)

        return client
    def onedrive_auth_own_app_cli():
        redirect_uri = 'http://localhost:5000/login/authorized'
        client_secret = 'bnQV76$%^inqsaDBRKG479#'
        client_id = 'c8e4b648-3fc8-4948-8c59-0b14d8972582'
        api_base_url = 'https://api.onedrive.com/v1.0/'
        scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(http_provider=http_provider,
                                                 client_id=client_id,
                                                 scopes=scopes)

        client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                            http_provider)
        auth_url = client.auth_provider.get_auth_url(redirect_uri)
        # Ask for the code
        print('Paste this URL into your browser, approve the app\'s access.')
        print(
            'Copy everything in the address bar after "code=", and paste it below.'
        )
        print(auth_url)
        code = input('Paste code here: ')

        client.auth_provider.authenticate(code, redirect_uri, client_secret)

        return client
Example #4
0
    def __init__(self, config):
        redirect_uri = "http://" + config["webService"]["name"] + ":" + str(config["webService"]["port"])
        client_secret = config["oneDrive"]["clientSecret"]
        client_id = config["oneDrive"]["clientId"]
        api_base_url = config["oneDrive"]["url"]
        scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(
            http_provider=http_provider,
            client_id=client_id,
            scopes=scopes)

        loaded = True
        #reload session ??
        try:
            auth_provider.load_session()
            auth_provider.refresh_token()
        except:
            loaded = False
        #reload session ??


        self.client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
        if loaded == False :
            auth_url = self.client.auth_provider.get_auth_url(redirect_uri)
            # Ask for the code
            print('Paste this URL into your browser, approve the app\'s access.')
            print('Copy everything in the address bar after "code=", and paste it below.')
            print(auth_url)
            code = input('Paste code here: ')

            self.client.auth_provider.authenticate(code, redirect_uri, client_secret)

        auth_provider.save_session()
Example #5
0
    def __init__(self, get_ids=True):
        self.client_id = '6a2475f8-6ae9-4c3d-a115-2a67794947df'
        self.api_base_url = 'https://api.onedrive.com/v1.0/'
        self.scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
        self.base_url = 'https://api.onedrive.com/v1.0/'
        self.data_path = os.environ['ECHR_OD_PATH']
        self.one_drive_structure = {}
        self.dataset = 'datasets_documents'
        self.articles = [
            'article_1.zip', 'article_2.zip', 'article_3.zip', 'article_5.zip',
            'article_6.zip', 'article_8.zip', 'article_10.zip',
            'article_11.zip', 'article_13.zip', 'article_34.zip',
            'article_p1.zip'
        ]
        self.n_gram = None
        self.token = None

        # OAuth part to One Drive
        while True:
            try:
                self.http_provider = onedrivesdk.HttpProvider()
                self.auth_provider = onedrivesdk.AuthProvider(
                    self.http_provider, self.client_id, self.scopes)
                self.auth_provider.load_session()
                self.auth_provider.refresh_token()
                self.client = onedrivesdk.OneDriveClient(
                    self.base_url, self.auth_provider, self.http_provider)
                # Check files IDs
                if get_ids:
                    self.get_files_ids()
                break
            except Exception as e:
                print(e)
                continue
Example #6
0
def auth_client():
    redirect_uri = 'http://localhost:8080/'
    client_secret = r'yjdWQS35{&({ofdcZWMM742'
    client_id = '576bca9f-5e74-440e-85fb-9025c984b5f6'
    api_base_url = 'https://api.onedrive.com/v1.0/'
    scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']

    http_provider = onedrivesdk.HttpProvider()
    auth_provider = onedrivesdk.AuthProvider(http_provider=http_provider,
                                             client_id=client_id,
                                             scopes=scopes)
    client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                        http_provider)
    try:
        auth_provider.load_session()
        auth_provider.refresh_token()

    except:
        auth_url = client.auth_provider.get_auth_url(redirect_uri)
        # Ask for the code
        print('Paste this URL into your browser, approve the app\'s access.')
        print(
            'Copy everything in the address bar after "code=", and paste it below.'
        )
        print(auth_url)
        code = input('Paste code here: ')
        auth_provider.authenticate(code, redirect_uri, client_secret)
        auth_provider.save_session()
    return client
Example #7
0
    def test_method_body_format(self, MockHttpProvider, MockAuthProvider):
        """
        Test that the parameters are correctly entered into the body of the message
        of methods that require this
        """
        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider,
                                            auth_provider)

        ref = ItemReference()
        ref.id = "testing!id"

        copy_request = client.drives["me"].items["testitem!id"].copy(
            parent_reference=ref, name="newName").request()
        assert copy_request.request_url == "onedriveurl/drives/me/items/testitem!id/action.copy"

        expected_dict = {
            "parentReference": {
                "id": "testing!id"
            },
            "name": "newName"
        }
        assert all(item in copy_request.body_options.items()
                   for item in expected_dict.items())
Example #8
0
def init_business(client):
    """onedrivesdk.request.one_drive_client.OneDriveClient->onedrivesdk.request.one_drive_client.OneDriveClient
    
    Important: Only used for Business/Office 365! 
    
    Init of the script.
    
    Let user login, get the details, save the details in a conf file.
    
    Used at the first time login.
    
    Ref:
    https://github.com/OneDrive/onedrive-sdk-python#onedrive-for-business
    https://dev.onedrive.com/auth/aad_oauth.htm#register-your-app-with-azure-active-directory
    """
    # auth url:
    # 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

    http = onedrivesdk.HttpProvider()
    auth = onedrivesdk.AuthProvider(http,
                                    client_id_business,
                                    auth_server_url=auth_server_url,
                                    auth_token_url=auth_token_url)
    auth_url = auth.get_auth_url(redirect_uri)

    # 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"

    auth_url = auth_url.encode('utf-8').replace("('", '').replace("',)", '')

    # Ask for the code
    print('ATTENTION: This is for Onedrive Business and Office 365 only.')
    print('If you are using normal Onedrive, lease exit and run')
    print('')
    print('onedrivecmd init')
    print('')
    print(auth_url)
    print('')
    print('Paste this URL into your browser, approve the app\'s access.')
    print('Copy all the code in the new window, and paste it below:')

    code = input('Paste code here: ')

    auth.authenticate(code,
                      redirect_uri,
                      client_secret_business,
                      resource='https://api.office.com/discovery/')

    # this step is slow
    service_info = ResourceDiscoveryRequest().get_service_info(
        auth.access_token)[0]

    auth.redeem_refresh_token(service_info.service_resource_id)

    client = onedrivesdk.OneDriveClient(
        service_info.service_resource_id + '_api/v2.0/', auth, http)

    #print(client)

    return client
Example #9
0
    def _get_client(self):
        if not self._client:
            self._client = onedrivesdk.OneDriveClient(self._api_base_url,
                                                      self._auth_provider,
                                                      self._http_provider)
            self._logger.debug("OneDrive client created")

        return self._client
Example #10
0
class Main():
    http_provider = onedrivesdk.HttpProvider()
    auth_provider = onedrivesdk.AuthProvider(http_provider, application_id,
                                             scopes)
    client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                        http_provider)

    def auth(auth_provider, client):
        try:
            auth_provider.load_session()
            auth_provider.refresh_token()
        except IOError:
            auth_url = client.auth_provider.get_auth_url(redirect_uri)
            print(
                'Paste this URL into your browser, approve the app\'s access.')
            print(
                'Copy everything in the address bar after "code=", and paste it below.'
            )
            print(auth_url)
            code = raw_input('Paste code here: ')
            auth_provider.authenticate(code, redirect_uri, client_secret)
            auth_provider.save_session()
        return client

    def get_sharing_link(client, return_file):
        global share
        permission = client.item(id=return_file.id).create_link("view").post()
        share = requests.get("{}".format(permission.link.web_url)).url.replace(
            'redir', 'download')
        return share

    def get_deleting(name, auth_provider, client):
        collection = client.item(drive='me',
                                 id='root').children.request(top=100).get()
        for item in collection:
            if item.name == name:
                client.item(id=item.id).delete()
                print u'Каталог удален'

    def get_upload(client, get_sharing_link):
        f = onedrivesdk.Folder()
        i = onedrivesdk.Item()
        i.name = FOLDER_NAME
        i.folder = f
        retur_folder = client.item(drive='me', id='root').children.add(i)
        try:
            return_file = client.item(
                drive='me',
                id=retur_folder.id).children['%s' %
                                             FILE_NAME].upload(FILE_UPLOAD)
            get_sharing_link(client, return_file)
            print share
        except IOError:
            print u'Файл не найден'

    auth(auth_provider, client)
    #get_upload(client, get_sharing_link)
    get_deleting(FOLDER_NAME, auth_provider, client)
Example #11
0
 def __init__(self,token,client_id):
     self.token = token
     scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
     http_provider = onedrivesdk.HttpProvider()
     auth_provider = onedrivesdk.AuthProvider(
         http_provider=http_provider,
         client_id=client_id,
         scopes=scopes)
     self.client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
Example #12
0
 def __init__(self):
     self.http_provider = onedrivesdk.HttpProvider()
     self.auth_provider = onedrivesdk.AuthProvider(
         http_provider=self.http_provider,
         client_id=client_id,
         scopes=scopes)
     self.client = onedrivesdk.OneDriveClient(graph_base_url,
                                              self.auth_provider,
                                              self.http_provider)
Example #13
0
 def reconnect(self):
     http_provider = onedrivesdk.HttpProvider()
     auth_provider = onedrivesdk.AuthProvider(http_provider, self.client_id,
                                              self.scopes)
     auth_provider.load_session()
     auth_provider.refresh_token()
     self.client = onedrivesdk.OneDriveClient(self.api_base_url,
                                              auth_provider, http_provider)
     self.isconnected = True
Example #14
0
def authenticate_and_get_client():
    assert 'CLIENT_ID' in os.environ, 'CLIENT_ID is not set for this environment'
    assert 'CLIENT_SECRET' in os.environ, 'CLIENT_SECRET is not set for this environment'

    client_id = os.environ.get('CLIENT_ID')
    client_secret = os.environ.get('CLIENT_SECRET')

    redirect_uri = 'http://localhost:8080/'

    api_base_url = 'https://api.onedrive.com/v1.0/'
    scopes = ['wl.signin', 'wl.offline_access', 'onedrive.readonly']

    http_provider = onedrivesdk.HttpProvider()
    auth_provider = onedrivesdk.AuthProvider(http_provider=http_provider,
                                             client_id=client_id,
                                             scopes=scopes)

    session_path = os.path.expanduser('~/.onedrive-utils.session.pickle')

    try:
        auth_provider.load_session(path=session_path)

        auth_provider.refresh_token()

        client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                            http_provider)

    except:
        client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                            http_provider)
        auth_url = client.auth_provider.get_auth_url(redirect_uri)
        # Ask for the code
        print('Paste this URL into your browser, approve the app\'s access.')
        print(
            'Copy everything in the address bar after "code=", and paste it below.'
        )
        print(auth_url)
        code = input('Paste code here: ')

        client.auth_provider.authenticate(code, redirect_uri, client_secret)

        auth_provider.save_session(path=session_path)

    return client
Example #15
0
def auth(account):
    client_secret = creds[account][0]
    client_id = creds[account][1]
    http_provider = onedrivesdk.HttpProvider()
    auth_provider = onedrivesdk.AuthProvider(http_provider, client_id, scopes)
    auth_provider.load_session()
    auth_provider.refresh_token()
    client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                        http_provider)
    return client
Example #16
0
def load_session(client, path = ''):
    """str->Client
    
    Load a new client from the saved status file.
    """
    ## helper: making a Session from dict we get from session file
    # main entrance of function to come after this function
    def make_session_from_dict(status_dict):
        return onedrivesdk.auth_provider.Session(status_dict['client.auth_provider._session']['token_type'], 
                                                         status_dict['client.auth_provider._session']['_expires_at'] - time(), 
                                                         status_dict['client.auth_provider._session']['scope_string'], 
                                                         status_dict['client.auth_provider._session']['access_token'], 
                                                         status_dict['client.auth_provider._session']['client_id'], 
                                                         status_dict['client.auth_provider._session']['auth_server_url'], 
                                                         status_dict['client.auth_provider._session']['redirect_uri'], 
                                                         refresh_token=status_dict['client.auth_provider._session']['refresh_token'], 
                                                         client_secret=status_dict['client.auth_provider._session']['client_secret'])

    ## start of function
    ## Read Session file
    try:
        with open(path, 'r') as session_file:
            status_dict = json.loads(session_file.read())
    except IOError as e:
        # file not exist or some other problems...
        logging.fatal(e.strerror)
        logging.fatal('Cannot read the session file!')
        exit()  #have to die now, or what else can we do?

    ## deterime type of account, run different logics
    # Business
    if status_dict['is_business']:
        # mock http and auth
        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(http_provider,
                                        client_id_business,
                                        auth_server_url=status_dict['client.auth_provider.auth_server_url'],
                                        auth_token_url=status_dict['client.auth_provider.auth_token_url'])

    else:
        # personal
        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(
            http_provider=http_provider,
            client_id=status_dict['client_id'],
            scopes=scopes)

    ## inject a Session in
    auth_provider._session = make_session_from_dict(status_dict)
    
    auth_provider.refresh_token()

    ## put API endpoint in
    return  onedrivesdk.OneDriveClient(status_dict['client.base_url'], auth_provider, http_provider)
Example #17
0
def getOneDriveClient():
    http_provider = onedrivesdk.HttpProvider()

    auth_provider = onedrivesdk.AuthProvider(
        http_provider=http_provider,
        client_id=settings.ONEDRIVE_API_CLIENTID,
        scopes=['onedrive.readwrite'],
        session_type=OneDriveSession)

    return onedrivesdk.OneDriveClient('https://api.onedrive.com/v1.0/',
                                      auth_provider, http_provider)
Example #18
0
def reload_setup():
    scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']
    api_base_url='https://api.onedrive.com/v1.0/'
    client_id='339f450f-3701-42ef-bcaa-a0b35a369c18'
    http_provider = onedrivesdk.HttpProvider()
    auth_provider = onedrivesdk.AuthProvider(http_provider,
                                             client_id,
                                             scopes)
    auth_provider.load_session()
    auth_provider.refresh_token()
    client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
    return client
Example #19
0
 def __init__(self):
     proxies = getproxies()
     if len(proxies) == 0:
         http_provider = onedrivesdk.HttpProvider()
     else:
         from onedrivesdk.helpers.http_provider_with_proxy import HttpProviderWithProxy
         http_provider = HttpProviderWithProxy(proxies, verify_ssl=True)
     auth_provider = onedrivesdk.AuthProvider(http_provider=http_provider,
                                              client_id=self.APP_CLIENT_ID,
                                              session_type=od_api_session.OneDriveAPISession,
                                              scopes=self.APP_SCOPES)
     self.client = onedrivesdk.OneDriveClient(self.APP_BASE_URL, auth_provider, http_provider)
    def test_path_creation_with_query(self, MockHttpProvider, MockAuthProvider):
        """
        Tests that a path is created with the correct query parameters
        """
        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider, auth_provider)

        request = client.drives["me"].items["root"].children.request(top=3, select="test")

        query_dict = dict(parse_qsl(urlparse(request.request_url).query))
        expected_dict = {"select":"test", "top":"3"}
        assert all(item in query_dict.items() for item in expected_dict.items())
    def test_path_creation(self, MockHttpProvider, MockAuthProvider):
        """
        Tests that the path of a request is resolved correctly
        """
        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider, auth_provider)

        request = client.drives["me"].items["root"].children.request()
        assert request.request_url == "onedriveurl/drives/me/items/root/children"

        request = client.drives["me"].items["root"].children["testfile.txt"].request()
        assert request.request_url == "onedriveurl/drives/me/items/root/children/testfile.txt"
Example #22
0
    def mauthenticator(self):
        self.get_local_auth_data()

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(http_provider=http_provider,
                                                 client_id=self.client_id,
                                                 scopes=scopes)

        try:
            open(self.SESSION_FILE)
            session_exists = True
        except FileNotFoundError:
            session_exists = False

        if session_exists:
            auth_provider.load_session(path=self.SESSION_FILE)
            auth_provider.refresh_token()

            client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                                http_provider)
        else:
            client = onedrivesdk.OneDriveClient(api_base_url, auth_provider,
                                                http_provider)

            auth_url = client.auth_provider.get_auth_url(redirect_uri)
            # Ask for the code
            print(
                'Paste this URL into your browser, approve the app\'s access.')
            print(
                'Copy everything in the address bar after "code=", and paste it below.'
            )
            print(auth_url)
            code = input('Paste code here: ')

            client.auth_provider.authenticate(code, redirect_uri,
                                              self.client_secret)
            client.auth_provider.save_session(path=self.SESSION_FILE)

        return client
Example #23
0
    def list_drives(self, credentials):
        """
        Lists all available drives and their types for given Microsoft OneDrive credentials.

        .. examples(websocket)::

            :::javascript
            {
              "id": "6841f242-840a-11e6-a437-00e04d680384",
              "msg": "method",
              "method": "cloudsync.onedrive_list_drives",
              "params": [{
                "client_id": "...",
                "client_secret": "",
                "token": "{...}",
              }]
            }

        Returns

            [{"drive_type": "PERSONAL", "drive_id": "6bb903a25ad65e46"}]
        """
        self.middleware.call_sync("network.general.will_perform_activity",
                                  "cloud_sync")

        if not credentials["client_id"]:
            credentials["client_id"] = "b15665d9-eda6-4092-8539-0eec376afd59"
        if not credentials["client_secret"]:
            credentials["client_secret"] = "qtyfaBBYA403=unZUP40~_#"

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(
            http_provider, session_type=RcloneTokenSession, loop=object())
        auth_provider.load_session(**credentials)
        auth_provider.refresh_token()

        client = onedrivesdk.OneDriveClient(
            "https://graph.microsoft.com/v1.0/",
            auth_provider,
            http_provider,
            loop=object())
        result = []
        for drive in client.drives.get().drives():
            result.append({
                "drive_type":
                DRIVES_TYPES.inverse.get(drive.drive_type, ""),
                "drive_id":
                drive.id,
            })
        return result
Example #24
0
def get_onedrive_client(loop):
    http_provider = onedrivesdk.HttpProvider()
    auth_provider = onedrivesdk.AuthProvider(
        http_provider=http_provider,
        auth_server_url=
        'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
        auth_token_url=
        'https://login.microsoftonline.com/common/oauth2/v2.0/token',
        client_id=ONEDRIVE_CLIENT_ID,
        scopes=ONEDRIVE_SCOPES.split(),
        loop=loop)
    client = onedrivesdk.OneDriveClient('https://graph.microsoft.com/v1.0/me/',
                                        auth_provider, http_provider)
    return client
Example #25
0
    def authenticate(self, code):
        print('Athenticating...')
        self.auth_provider.authenticate(code, self.APP_REDIRECT_URL, self.APP_CLIENT_SECRET_BUSINESS, resource=self.APP_DISCOVERY_URL_BUSINESS)
        
        # this step can be slow
        service_info = ResourceDiscoveryRequest().get_service_info(self.auth_provider.access_token)

        self.APP_ENDPOINT = str(service_info[0]).split()[1]

        print('Refreshing token...')
        self.auth_provider.redeem_refresh_token(self.APP_ENDPOINT)
        print('Updating client')
        self.client = onedrivesdk.OneDriveClient(self.APP_ENDPOINT + '_api/v2.0/', self.auth_provider, self.http_provider)
        print('Authenticated!')
Example #26
0
    def test_polling_background_method(self, MockHttpProvider,
                                       MockAuthProvider):
        """
        Test that polling in the background actually functions as it should and polls
        on a seperate thread.
        """
        response = HttpResponse(301, {"Location": "statusLocation"}, "")
        instance_http = MockHttpProvider.return_value
        instance_http.send.return_value = response

        instance_auth = MockAuthProvider.return_value
        instance_auth.authenticate.return_value = "blah"
        instance_auth.authenticate_request.return_value = None

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider,
                                            auth_provider)

        ref = ItemReference()
        ref.id = "testing!id"
        mock = Mock()

        copy_operation = client.drives["me"].items["testitem!id"].copy(
            parent_reference=ref, name="newName").request().post()

        response = HttpResponse(
            200, None,
            json.dumps({
                "operation": "copy",
                "percentageComplete": 0,
                "status": "In progress"
            }))
        instance_http.send.return_value = response

        time.sleep(0.2)

        assert copy_operation.item is None

        response = HttpResponse(
            200, None, json.dumps({
                "id": "testitem!id",
                "name": "newName"
            }))
        instance_http.send.return_value = response

        time.sleep(0.1)

        assert copy_operation.item is not None
Example #27
0
    def __init__(self, c, rc_model):
        self.config = c
        self.rc_model = rc_model

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(
            http_provider=http_provider,
            client_id=c.ms_app_id,
            scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite'])

        self.client = onedrivesdk.OneDriveClient(
            'https://api.onedrive.com/v1.0/', auth_provider, http_provider)

        auth_provider.load_session()
        auth_provider.refresh_token()
    def test_method_query_format(self, MockHttpProvider, MockAuthProvider):
        """
        Test that the parameters are correctly entered into the query string
        of the request for methods that require this
        """
        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider()
        client = onedrivesdk.OneDriveClient("onedriveurl/", http_provider, auth_provider)

        changes_request = client.drives["me"].items["testitem!id"].delta(token="token").request()
        assert urlparse(changes_request.request_url).path == "onedriveurl/drives/me/items/testitem!id/view.delta"

        query_dict = dict(parse_qsl(urlparse(changes_request.request_url).query))
        expected_dict = {"token":"token"}
        assert all(item in query_dict.items() for item in expected_dict.items())
Example #29
0
    def __init__(self, endpoint=None):
        proxies = getproxies()
        if len(proxies) == 0:
            self.http_provider = onedrivesdk.HttpProvider()
        else:
            from onedrivesdk.helpers.http_provider_with_proxy import HttpProviderWithProxy
            self.http_provider = HttpProviderWithProxy(proxies, verify_ssl=True)

        self.auth_provider = onedrivesdk.AuthProvider(self.http_provider,
                                                 self.APP_CLIENT_ID_BUSINESS,
                                                 session_type=od_api_session.OneDriveAPISession,
                                                 auth_server_url=self.APP_AUTH_SERVER_URL_BUSINESS,
                                                 auth_token_url=self.APP_TOKEN_URL_BUSINESS)

        if (endpoint is not None):
            self.client = onedrivesdk.OneDriveClient(endpoint + '_api/v2.0/', self.auth_provider, self.http_provider)
Example #30
0
    def __init_service(self):
        api_base_url = self.__config.get('onedrive', 'onedrive.api_base_url')
        client_id = self.__config.get('onedrive', 'onedrive.client_id')
        session_file = self.__config.get('onedrive', 'onedrive.session_file')

        if not exists(session_file):
            self.__save_credentials(session_file)

        http_provider = onedrivesdk.HttpProvider()
        auth_provider = onedrivesdk.AuthProvider(http_provider, client_id,
                                                 self.__scopes)

        # Load the session
        auth_provider.load_session(path=session_file)
        auth_provider.refresh_token()
        self.__onedrive_service = onedrivesdk.OneDriveClient(
            api_base_url, auth_provider, http_provider)