예제 #1
0
 def login(self):
     try:
         self.__site_url = StringUtils.StringUtils.websiteAPI
         self.__ctx = ClientContext(self.__site_url).with_credentials(
             UserCredential(StringUtils.StringUtils.email, StringUtils.StringUtils.passwort))
     except ValueError:
         raise LoginException
    def __init__(self, url, username, password, log):
        """
        SharePoint object initialization.
        :param url: SharePoint destination URL (See DEFAULT_SP_URL above for example)
        :param username: Username to access SharePoint (See DEFAULT_SP_USERNAME above for example)
        :param log: where to send log messages
        :type log: logging.Logger
        """
        self._url = url
        self._username = username
        self._password = password
        self.log = log

        #
        # Authenticate for this run
        #
        log.debug(
            "SharePoint: Acquiring AuthenticationContext {} for {}".format(
                url, username))
        self._ctx_auth = AuthenticationContext(url=url)

        #
        # Looks like, at the time of this writing, the Office365-REST_Python-Client
        # library exception handling leaves a lot to be desired as their internal
        # method calls don't test the results of lower-level method calls in order to
        # percolate up problems they encounter.
        #
        # NOTE: Errors will actually go to the log file but not standard output for some
        #       unknown reason
        #
        log.debug("SharePoint: Acquiring token from {} for {}".format(
            url, username))
        self._ctx_auth.acquire_token_for_user(username=username,
                                              password=password)

        #
        # Kludgy test to see if a problem occurred
        # Admittedly this test will break if a different authentication provider is used
        #
        if self._ctx_auth.provider.token is None:
            _msg = "SharePoint: Unable to get SharePoint authorization. Error: {}".format(
                self._ctx_auth.get_last_error())
            log.critical(_msg)
            raise ValueError(_msg)

        log.debug(
            "SharePoint: Authentication token obtained from {} for {}".format(
                url, username))

        #
        # Get cookies
        #
        log.debug("SharePoint: Getting cookies from {} for {}".format(
            url, username))
        self._ctx = ClientContext(self.url, self._ctx_auth)
        log.debug("SharePoint: Obtained ClientContext from {} for {}".format(
            url, username))
    def __init__(self, settings_path):
        super().__init__(__version__, r"/home/downloader_settings",
                         settings_path)
        context_auth = AuthenticationContext(url=site_url)
        context_auth.acquire_token_for_app(
            client_id=app_principal['client_id'],
            client_secret=app_principal['client_secret'])

        self.ctx = ClientContext(site_url, context_auth)
예제 #4
0
    def test_10_execute_update_batch_request(self):
        client = ClientContext(test_site_url).with_credentials(test_user_credentials)
        web = client.web
        new_web_title = create_unique_name("Site")
        web.set_property("Title", new_web_title).update()
        client.execute_batch()

        updated_web = client.web.get().execute_query()
        self.assertEqual(updated_web.properties['Title'], new_web_title)
    def test_11_execute_get_and_update_batch_request(self):
        page_url = "/sites/team/SitePages/Home.aspx"
        client = ClientContext(test_team_site_url).with_credentials(
            test_user_credentials)
        list_item = client.web.get_file_by_server_relative_url(
            page_url).listItemAllFields
        new_title = create_unique_name("Page")
        list_item.set_property("Title", new_title).update()
        client.execute_batch()

        updated_list_item = client.web.get_file_by_server_relative_url(
            page_url).listItemAllFields.get().execute_query()
        self.assertEqual(updated_list_item.properties['Title'], new_title)
    def test_16_ensure_property(self):
        client = ClientContext(test_site_url).with_credentials(
            test_user_credentials)
        me = client.web.current_user.get()
        site = client.site

        def _owner_loaded():
            self.assertIsNotNone(site.owner.id)

        site.ensure_property("Owner", _owner_loaded).get()
        lib = client.web.default_document_library().get()
        client.execute_query()
        self.assertIsNotNone(me.login_name)
        self.assertIsNotNone(lib.title)
예제 #7
0
    def upload_files(self):
        """
        Upload files from configuration to the Sharepoint site from the configuration.
        """

        ctx = ClientContext(self._url, self._context_auth)
        root = ctx.web.lists.get_by_title("Documents").root_folder
        target_folder = root.folders.get_by_url(self._fconfig.out_folder)
        file_size = 0

        for f in self._fconfig.files:
            self._logger.info(f"File upload: {os.path.basename(f)}")
            file_size = os.path.getsize(f)

            with tqdm(
                    total=file_size,
                    file=sys.stdout,
                    unit="B",
                    unit_scale=True,
                    unit_divisor=1024,
                    ascii=True,
            ) as pbar:

                def display_upload_progress(offset):  # pylint: disable=unused-argument
                    # print_progress callback in create_upload_session requires
                    # the offset parameter to show progress like:
                    #  (`offset` out of `file_size` uploaded)
                    # but tqdm instead works with `chunk_size`, i.e. size of step to
                    # update the progress bar.
                    """
                    Callback used to print progress to stdout during file update.
                    """

                    # pbar is only ever used here, so it's safe to silence
                    # the warning from pylint.
                    pbar.update(  # pylint: disable=cell-var-from-loop
                        self._runtime.chunk_size)

                uploaded_file = target_folder.files.create_upload_session(
                    f, self._runtime.chunk_size, display_upload_progress)
                try:
                    ctx.execute_query()
                except ClientRequestException as err:
                    self._logger.error(err.args[self._MESSAGE])
                    return False

            self._logger.success(
                f"File {f} uploaded to: {uploaded_file.serverRelativeUrl}")

        return True
예제 #8
0
def alterarGeradas(ID, sumGeradas):
    # Definindo parametros de conexão
    # ID e Senha criados pelo portal do sharepoint
    app_settings = {
        'url': 'https://usinacoruripe.sharepoint.com/sites/FaturamentoTorta',
        'client_id': 'c74022f1-d1b5-47e3-913f-84d7a98cf032',
        'client_secret': 'qfHtOWl6YieOhGAAavzuzUDvuf9pl2ZvD/0JSqvZhsQ='
    }

    # Chamando conexão com API Rest
    context_auth = AuthenticationContext(url=app_settings['url'])
    context_auth.acquire_token_for_app(
        client_id=app_settings['client_id'],
        client_secret=app_settings['client_secret'])
    ctx = ClientContext(app_settings['url'], context_auth)

    # Puxando valores da lista
    listaShare = ctx.web.lists.get_by_title("Autorizações")
    items = listaShare.get_items()
    ctx.load(items)
    ctx.execute_query()

    item = listaShare.get_item_by_id(ID)
    item.set_property('OData__x006d_kv6', sumGeradas)
    item.update()
    ctx.execute_query()
 def test1_connect_with_app_principal(self):
     credentials = ClientCredential(
         settings.get('client_credentials').get('client_id'),
         settings.get('client_credentials').get('client_secret'))
     ctx = ClientContext(settings['url']).with_credentials(credentials)
     self.assertIsInstance(ctx.authentication_context._provider,
                           ACSTokenProvider)
예제 #10
0
 def setUpClass(cls):
     ctx_auth = AuthenticationContext(url=settings['url'])
     # ctx_auth.acquire_token_for_user(username=settings['user_credentials']['username'],
     #                                password=settings['user_credentials']['password'])
     ctx_auth.acquire_token_for_app(client_id=settings['client_credentials']['client_id'],
                                    client_secret=settings['client_credentials']['client_secret'])
     cls.context = ClientContext(settings['url'], ctx_auth)
예제 #11
0
    def execute(self, container, args):
        l = self.logger

        try:

            try:
                ctx_auth = AuthenticationContext(url=args.sharepointurl)
                if ctx_auth.acquire_token_for_user(
                        username=args.sharepointusername,
                        password=args.sharepointpass):
                    ctx = ClientContext(args.sharepointurl, ctx_auth)
                    filename = args.output
                    path = args.sharepointfpath
                    checkin_type = args.uplshr_checkintype
                    return upload_data_to_sharepoint(path, filename, ctx,
                                                     checkin_type, l)
                else:
                    print(ctx_auth.get_last_error())
                    return

            except Exception as e:
                l.error("Exception happened boards search " + str(e))

        except Exception as e:
            l.error("Exception happened during connection establishment " +
                    str(e))
예제 #12
0
def __upload_target_reports(adm_sp_value: ADMSharepointValue) -> None:
    site_url = adm_sp_value.sharepoint_value.site_url + 'sites/' + adm_sp_value.sharepoint_value.site_id

    context_auth = AuthenticationContext(url=site_url)
    context_auth.acquire_token_for_app(
        client_id=adm_sp_value.sharepoint_value.client_id,
        client_secret=adm_sp_value.sharepoint_value.client_secret)
    ctx = ClientContext(site_url, context_auth)

    target_report_values = adm_sp_value.target_report_values

    # Create folder structure
    new_path = __create_folder(ctx, adm_sp_value)

    # Upload reports without segment by configuration
    if target_report_values is not None:
        for target_report_value in target_report_values:
            file_path = target_report_value.target_report_location
            if file_path is not None:
                files = glob.glob(file_path)
                __upload_file(files, new_path, ctx)

            # Upload reports with segment by configuration
            target_report_segment_values = target_report_value.target_report_segment_values
            if target_report_segment_values is not None:
                for target_report_segment_value in target_report_segment_values:
                    segment_by_value = target_report_segment_value.target_report_segment_by_field_value
                    segment_file_path = target_report_segment_value.target_report_segment_report_location
                    segment_files = glob.glob(segment_file_path)
                    __upload_file(segment_files, new_path, ctx,
                                  segment_by_value)
예제 #13
0
 def setUpClass(cls):
     super(TestCommunicationSite, cls).setUpClass()
     ctx_auth = AuthenticationContext(url=settings['url'])
     ctx_auth.acquire_token_for_user(username=settings['user_credentials']['username'],
                                     password=settings['user_credentials']['password'])
     cls.client = ClientContext(settings['url'], ctx_auth)
     cls.site_manager = SPSiteManager(cls.client)
예제 #14
0
def upload_one_excel(configuration, f, people, folders):
    spbase = configuration['sharepointbase']
    sharepointlibrary = configuration['sharepointlibrary']
    spbase = configuration['sharepointbase']
    test_team_site_url = configuration['sharepointsite']
    sharepointlibrary = configuration['sharepointlibrary']

    cred = get_user_credentials()
    ctx = ClientContext(test_team_site_url).with_user_credentials(cred['username'], cred['password'])

    centro = '00_Generale'
    for c, o in people.items():
        for organizer in o:
            if organizer in path.basename(f):
                centro = c

    file_date = datetime.strptime(path.basename(f)[:10], '%Y-%m-%d')
    
    for d in folders:
        folder = '%s_Report Teams' % d.strftime("%Y-%m-%d")

        if file_date <= d:
            newpath = path.join(sharepointlibrary, spbase, centro, 'Report FAD', folder)
            target_folder = ctx.web.ensure_folder_path(newpath).execute_query()
            
            with open(f, 'rb') as content_file:
                file_content = content_file.read()

            name = path.basename(f)
            target_file = target_folder.upload_file(name, file_content).execute_query()

            if target_file:
                return [{'origin': f, 'destination': target_file.serverRelativeUrl}]
                
            return None
    def setUpClass(cls):
        super(TestCommunicationSite, cls).setUpClass()
        cls.user_credentials = UserCredential(settings['user_credentials']['username'],
                                              settings['user_credentials']['password'])

        cls.client = ClientContext(settings['url']).with_credentials(cls.user_credentials)
        cls.site_manager = SPSiteManager(cls.client)
예제 #16
0
    def setUpClass(cls):
        credentials = UserCredential(settings['user_credentials']['username'],
                                     settings['user_credentials']['password'])

        cls.client = ClientContext(
            settings.get("admin_site_url")).with_credentials(credentials)
        cls.tenant = Tenant(cls.client)
예제 #17
0
    def __init__(self,
                 host,
                 port=0,
                 auth=None,
                 username=None,
                 password=None,
                 protocol='http',
                 path=None):
        if not port:
            port = 443 if protocol == 'https' else 80
        self.path = path or ''
        if not self.path.endswith('/'):
            self.path = '%s/' % self.path

        # oneDrive: need to split /site/ and path
        # in our config site is /personal/UF_OCX_msf_geneva_msf_org/
        # path is /Documents/Tests/
        self.baseurl = '{0}://{1}:{2}{3}/'.format(
            protocol, host, port, '/'.join(self.path.split('/')[0:3]))
        ctx_auth = AuthenticationContext(self.baseurl)

        #if len(self.path.split('/')) < 5:
        #    self.path = '%sDocuments/' % self.path
        if ctx_auth.acquire_token_for_user(username, cgi.escape(password)):
            self.request = ClientRequest(ctx_auth)
            self.request.context = ClientContext(self.baseurl, ctx_auth)

            if not ctx_auth.provider.FedAuth or not ctx_auth.provider.rtFa:
                raise ConnectionFailed(ctx_auth.get_last_error())
        else:
            raise ConnectionFailed(ctx_auth.get_last_error())
예제 #18
0
 def from_url(admin_site_url):
     """
     :type admin_site_url: str
     """
     from office365.sharepoint.client_context import ClientContext
     admin_client = ClientContext(admin_site_url)
     return Tenant(admin_client)
    def setUpClass(cls):
        super(TestTeamSite, cls).setUpClass()

        user_credentials = UserCredential(settings['user_credentials']['username'],
                                          settings['user_credentials']['password'])
        cls.client = ClientContext(settings['url']).with_credentials(user_credentials)
        cls.site_manager = GroupSiteManager(cls.client)
 def test3_register_hub_site(self):
     client_admin = ClientContext(test_admin_site_url).with_credentials(
         test_user_credentials)
     tenant = Tenant(client_admin)
     props = tenant.register_hub_site(
         self.__class__.site_response.SiteUrl).execute_query()
     self.assertIsNotNone(props)
예제 #21
0
 def test4_unregister_hub_site(self):
     admin_site_url = settings.get('admin_site_url')
     client_admin = ClientContext(admin_site_url).with_credentials(
         self.user_credentials)
     tenant = Tenant(client_admin)
     tenant.unregister_hub_site(
         self.__class__.site_response.SiteUrl).execute_query()
예제 #22
0
 def test1_connect_with_app_principal(self):
     credentials = ClientCredential(settings.get('client_credentials').get('client_id'),
                                    settings.get('client_credentials').get('client_secret'))
     ctx = ClientContext.connect_with_credentials(settings['url'], credentials)
     self.assertIsInstance(ctx.authentication_context.provider, ACSTokenProvider)
     self.assertIsInstance(ctx.authentication_context.provider.token, TokenResponse)
     self.assertTrue(ctx.authentication_context.provider.token.is_valid)
예제 #23
0
 def test9_execute_get_batch_request(self):
     client = ClientContext(test_site_url).with_credentials(test_user_credentials)
     current_user = client.web.current_user
     client.load(current_user)
     current_web = client.web
     client.load(current_web)
     client.execute_batch()
     self.assertIsNotNone(current_web.url)
     self.assertIsNotNone(current_user.user_id)
예제 #24
0
 def test8_execute_multiple_queries_sequentially(self):
     client = ClientContext(test_site_url).with_credentials(test_user_credentials)
     current_user = client.web.current_user
     client.load(current_user)
     current_web = client.web
     client.load(current_web)
     client.execute_query()
     self.assertIsNotNone(current_web.url)
     self.assertIsNotNone(current_user.user_id)
예제 #25
0
 def test5_get_batch_request(self):
     client = ClientContext(settings['url']).with_credentials(user_credentials)
     current_user = client.web.currentUser
     client.load(current_user)
     current_web = client.web
     client.load(current_web)
     client.execute_batch()
     self.assertIsNotNone(current_web.url)
     self.assertIsNotNone(current_user.user_id)
class SharePoint():

    # Generating Auth Access
    auth = AuthenticationContext(sharepoint_base_url)
    auth.acquire_token_for_user(sharepoint_user, sharepoint_password)
    ctx = ClientContext(sharepoint_base_url, auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()
    print('Connected to SharePoint: ', web.properties['Title'])

    # Collecting files names from the folder
    def folder_details(ctx, folder_in_sharepoint):
        folder = ctx.web.get_folder_by_server_relative_url(
            folder_in_sharepoint)
        folder_names = []
        sub_folders = folder.files
        ctx.load(sub_folders)
        ctx.execute_query()
        for each_folder in sub_folders:
            folder_names.append(each_folder.properties["Name"])
        return folder_names

    # Passing auth ctx and folder path
    file_list = folder_details(ctx, folder_in_sharepoint)

    # Reading File from SharePoint Folder and saving it in local.
    print("Downloading 3P & Subledger file from sharepoint")
    for each_file in file_list:
        sharepoint_file = folder_in_sharepoint + each_file
        file_response = File.open_binary(ctx, sharepoint_file)
        print(file_response)

        with open(each_file, 'wb') as output_file:
            output_file.write(file_response.content)

    # Downloading the UTC Key file from the sharepoint
    print("Downloading UTC Key.xlsx file from sharepoint")
    sharepoint_file = utc_key_file_in_sharepoint + "UTC Key.xlsx"
    file_response = File.open_binary(ctx, sharepoint_file)
    print(file_response)
    with open("UTC Key.xlsx", 'wb') as output_file:
        output_file.write(file_response.content)

    # Processing the files and generating the output file.
    print("Processing the files and generating the output file")
    import automation

    # Uploading the output file in the output folder of sharepoint.
    with open(output_xlsx, 'rb') as content_file:
        print(output_xlsx)
        file_content = content_file.read()
        target_folder = ctx.web.get_folder_by_server_relative_url(
            '/CP/Shared%20Documents/Automation/Subledger%20Automation/Output/')
        print(
            "Uploading the output file in the output folder of the sharepoint."
        )
        target_folder.upload_file(output_xlsx, file_content)
        ctx.execute_query()
    def setUpClass(cls):
        tenant = os.environ.get('office365_python_sdk_tenant', 'mediadev8')
        admin_site_url = "https://{0}-admin.sharepoint.com/".format(tenant)
        credentials = UserCredential(settings['user_credentials']['username'],
                                     settings['user_credentials']['password'])

        cls.client = ClientContext(admin_site_url).with_credentials(credentials)
        cls.tenant = Tenant(cls.client)
 def setUpClass(cls):
     super(TestSearch, cls).setUpClass()
     user_credentials = UserCredential(
         settings['user_credentials']['username'],
         settings['user_credentials']['password'])
     cls.client = ClientContext(
         settings['url']).with_credentials(user_credentials)
     cls.search = SearchService(cls.client)
예제 #29
0
 def test2_connect_with_app_principal_alt(self):
     context_auth = AuthenticationContext(url=test_site_url)
     context_auth.acquire_token_for_app(
         client_id=settings.get('client_credentials', 'client_id'),
         client_secret=settings.get('client_credentials', 'client_secret'))
     ctx = ClientContext(test_site_url, context_auth)
     self.assertIsInstance(ctx.authentication_context._provider,
                           ACSTokenProvider)
예제 #30
0
    def from_url(url):
        """Construct and return a site instance

        :type url: str
        """
        from office365.sharepoint.client_context import ClientContext
        client = ClientContext(url)
        return client.site