Ejemplo n.º 1
0
def init_business(args, init=True):
    credentials, redirect_url = select_app(args)
    token_backend = get_token_backend(args)

    account = Account(credentials, token_backend=token_backend)
    if init:
        account.authenticate(
            scopes=["basic", "onedrive_all", "sharepoint_dl"],
            redirect_uri=redirect_url,
            # notice!!! redirect_uri(i) not l !!!
        )
    else:

        def get_token(self):
            token = self.con.token_backend.token
            if not token:
                token = self.con.token_backend.get_token()
            if token.is_access_expired:
                self.con.refresh_token()
                token = self.con.token_backend.token
            return token["access_token"]

        account.get_token = types.MethodType(get_token, account)

        return account
Ejemplo n.º 2
0
def auth_user():
    credentials = (CLIENT_ID, CLIENT_SECRET)

    scopes = ['basic', 'message_all']
    account = Account(credentials)
    if not account.is_authenticated:
        account.authenticate(scopes=scopes)
Ejemplo n.º 3
0
def function_microsoft():
    try:
        scopes = [
            'https://graph.microsoft.com/MailboxSettings.Read',
            'https://graph.microsoft.com/MailboxSettings.ReadWrite',
            'https://graph.microsoft.com/User.Read'
        ]  # you can use scope helpers here (see Permissions and Scopes section)
        token_backend = FileSystemTokenBackend(token_path='',
                                               token_filename='my_token.txt')
        #protocol = MSGraphProtocol(api_version='v1.0')
        account = Account(credentials, token_backend=token_backend)
        if not account.is_authenticated:
            account.authenticate(scopes=scopes)

        with open('my_token.txt', 'r') as myfile:
            data = myfile.read()

        obj = json.loads(data)

        access_token = obj['access_token']

        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer {0}'.format(access_token)
        }

        api_url = 'https://graph.microsoft.com/v1.0/me/mailboxSettings'

        response = requests.get(api_url, headers=headers)

        info = json.loads(response.content.decode('utf-8'))

        return (info['automaticRepliesSetting'])
    except:
        return {'reply': False}
Ejemplo n.º 4
0
def functionpost_microsoft(data):
    try:
        scopes = [
            'https://graph.microsoft.com/MailboxSettings.Read',
            'https://graph.microsoft.com/MailboxSettings.ReadWrite',
            'https://graph.microsoft.com/User.Read'
        ]  # you can use scope helpers here (see Permissions and Scopes section)
        token_backend = FileSystemTokenBackend(token_path='',
                                               token_filename='my_token.txt')
        #protocol = MSGraphProtocol(api_version='v1.0')
        account = Account(credentials, token_backend=token_backend)
        if not account.is_authenticated:
            account.authenticate(scopes=scopes)

        with open('my_token.txt', 'r') as myfile:
            tok = myfile.read()

        obj = json.loads(tok)

        access_token = obj['access_token']

        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer {0}'.format(access_token)
        }

        api_url = 'https://graph.microsoft.com/v1.0/me/mailboxSettings'

        info = {"automaticRepliesSetting": data}

        print('info is:::::')
        print(info)

        response = requests.patch(api_url, headers=headers, json=info)

        if response.status_code >= 500:
            print('[!] [{0}] Server Error'.format(response.status_code))
        elif response.status_code == 404:
            print('[!] [{0}] URL not found: [{1}]'.format(
                response.status_code, api_url))
        elif response.status_code == 401:
            print('[!] [{0}] Authentication Failed'.format(
                response.status_code))
        elif response.status_code >= 400:
            print('[!] [{0}] Bad Request'.format(response.status_code))
            print(info)
            print(response.content)
        elif response.status_code >= 300:
            print('[!] [{0}] Unexpected redirect.'.format(
                response.status_code))
        elif response.status_code == 200:
            posted_content = json.loads(response.content)
            return (posted_content)
        else:
            print('[?] Unexpected Error: [HTTP {0}]: Content: {1}'.format(
                response.status_code, response.content))

    except:
        return {'reply': False}
def init_auth():
    client_secret = "W9hAa7i62Uv?hLTLH-?BlxhRCYWIkj?A"
    application_id = "bdf4dd0c-9ba0-4bc2-b72f-d7ce5023f0b9"
    credentials = (application_id, client_secret)
    tenant_id = "17855ce0-d47e-48df-9c90-33b4fa21c861"
    account = Account(credentials,
                      auth_flow_type="credentials",
                      tenant_id=tenant_id)
    account.authenticate()
    return account
Ejemplo n.º 6
0
def init_o365(protocol: MSOffice365Protocol = MSOffice365Protocol(),
              credentials: Callable = o365_credentials,
              token_path: Path = O365_DEFAULT_TOKEN_PATH,
              scopes: List[str] = O365_DEFAULT_SCOPES):
    token_backend = FileSystemTokenBackend(token_path=token_path /
                                           O365_DEFAULT_TOKEN_FILE_NAME)
    account = Account(credentials(),
                      protocol=protocol,
                      token_backend=token_backend)

    if not account.is_authenticated and os.path.exists(
            os.path.join(token_path, O365_DEFAULT_TOKEN_FILE_NAME)):
        account.con.refresh_token()
    elif not account.is_authenticated:
        account.authenticate(scopes=scopes, grant_type='client_credentials')
    return account
Ejemplo n.º 7
0
def get_office365_account():
    credentials = (config_secrets.get('office365', 'client_id'),
                   config_secrets.get('office365', 'client_secret'))

    ensure_token_dir()

    token_backend = FileSystemTokenBackend(token_path=TOKEN_DIR,
                                           token_filename='token.txt')
    account = Account(credentials,
                      main_resource=config_secrets.get('office365',
                                                       'username'),
                      auth_flow_type='credentials',
                      tenant_id=config_secrets.get('office365', 'tenant_id'),
                      token_backend=token_backend)
    account.authenticate()
    return account
def get_team_data(team_id="955529db-5622-4dca-9c90-8cb0e5fe032f"):
    client_secret = "W9hAa7i62Uv?hLTLH-?BlxhRCYWIkj?A"
    application_id = "bdf4dd0c-9ba0-4bc2-b72f-d7ce5023f0b9"
    credentials = (application_id, client_secret)
    tenant_id = "17855ce0-d47e-48df-9c90-33b4fa21c861"
    account = Account(credentials,
                      auth_flow_type="credentials",
                      tenant_id=tenant_id)
    account.authenticate()

    team = Group(group_id=team_id, parent=account, protocol=MSGraphProtocol())

    print(team.get_id())
    response = team.get_reports()
    print(json.loads(response.text))
    with open('data.txt', 'w') as outfile:
        json.dump(response.text, outfile)
def o365_connect(**kwargs):
    """Connect to O365 and return an Account object"""
    credentials = (kwargs['client_id'], kwargs['client_secret'])

    #seems like next two lines only have to run once for the app! But we do have to find out how to automatically re-generate
    # tokens
    #result = oauth_authentication_flow(kwargs['client_id'], kwargs['client_secret'], kwargs['scopes', tenant_id=kwargs['tenant_id'])
    #print("auth flow result=",result)

    account = Account(credentials)

    if not account.is_authenticated:  # will check if there is a token and has not expired
        # ask for a login. After logging in, please paste the URL to which the login re-directed as an response
        # to the prompt in the terminal window and press enter. The new token text file will be generated in the same
        # directory where this python script is running from.
        account.authenticate(scopes=kwargs['scopes'])

    return account
def authenticate_outlook():
    # authenticate microsoft graph api credentials

    credentials = (config.outlook_client_id, config.outlook_client_secret)
    token_backend = FileSystemTokenBackend(
        token_path=config.outlook_token_path,
        token_filename=config.outlook_token_filename)
    account = Account(credentials, token_backend=token_backend)
    if not account.is_authenticated:
        # not authenticated, throw error
        account.authenticate(scopes=config.outlook_scopes)

    connection = Connection(credentials,
                            token_backend=token_backend,
                            scopes=config.outlook_scopes)
    connection.refresh_token()

    print("Authenticated Outlook.")
    return account
class Email():
    def __init__(self, filePath):
        self.filePath = filePath

        json_file = open('credentials.txt', 'r')
        data = json.load(json_file)
        self.client_id = data['client_id']
        self.client_secret = data['client_secret']

    def connect(self):
        credentials = (self.client_id, self.client_secret)
        scopes = ['Mail.Send', 'offline_access', 'Mail.ReadWrite', 'User.Read']
        self.account = Account(credentials)
        if not self.account.is_authenticated:  # will check if there is a token and has not expired
            # ask for a login
            self.account.authenticate(scopes=scopes)

    def send_email(self, error):
        self.connect()
        m = self.account.new_message()
        m.to.add([
            '*****@*****.**', '*****@*****.**',
            '*****@*****.**'
        ])
        #m.to.add(['*****@*****.**'])
        m.cc.add(['*****@*****.**'])
        m.subject = 'Error in R_Forcasting'

        if error != 'File Not Found in the Path':
            m.body = """Hi, <br><br>
                     There is an error while running the forecasting code.<br>
                     For more details Please find the attached log file. <br><br> 
                     <b> """ + error + """  </b> <br><br>Regards, <br> Code"""

            m.attachments.add(self.filePath)
        else:
            m.body = """Hi, <br><br>
                     There is an error while running the forecasting code.<br>
                     <b> """ + error + """  </b> <br><br>Regards, <br> Code"""

        m.send()
Ejemplo n.º 12
0
def main():
    config = read_yaml()
    credentials = (config["outlook"]["client_id"],
                   config["outlook"]["secret_id"])
    account = Account(credentials)
    if account.authenticate(scopes=['https://graph.microsoft.com/Mail.Send']):
        print('Authenticated!')
        m = account.new_message()
        m.to.add(config["outlook"]["test_email"])
        m.subject = 'Testing!'
        m.body = "Culero Incorparated."
        m.send()
Ejemplo n.º 13
0
def send_o365(api_key, secret, from_email, to_email, email_body, subject):

	credentials = (api_key, secret)
	tokenFile = "o365_token.txt"
	if not os.path.exists(os.path.exists(os.path.join(Path(__file__).parent, tokenFile))):
		logging.critical("o365 emailer cannot find token file. Sending emails will fail.")	

	token_backend = FileSystemTokenBackend(token_path=Path(__file__).parent, token_filename=tokenFile)

	account = Account(credentials, token_backend=token_backend, scopes=['message_send'])
	if not account.authenticate():
	#if not account.is_authenticated(scopes=['message_send']):
		account.authenticate()
		logging.critical("o365 emailer is not authenticated. Requires manual investigation.")

	example_mailbox = account.mailbox(resource=from_email)
	m = example_mailbox.new_message()
	m.to.add(to_email)
	m.subject = subject
	m.body = email_body
	m.send()
Ejemplo n.º 14
0
def fetchContactList(settings):
    if settings['delegated']:
        globalAccount = Account(
            (settings['client_id'], settings['client_secret']),
            scopes=['basic','users'],
            auth_flow_type='authorization',
            tenant_id=settings['tenant_id'])
    else:
        globalAccount = Account(
            (settings['client_id'], settings['client_secret']),
            auth_flow_type='credentials',
            tenant_id=settings['tenant_id'])

    #LOG.info("Authenticating...")
    if not globalAccount.is_authenticated:
        globalAccount.authenticate()
    
    #LOG.info("Retrieving contact list...")
    for userDetails in globalAccount.directory().get_users(limit=None):
        if userDetails.mail:
            print(userDetails.mail)
class OutlookCalendar(AbstractCalendar):
    client_id: str = None
    secret_id: str = None

    def __init__(self, config: Dict):
        self.client_id = config['client-id']
        self.secret_id = config['secret-id']
        self.calendar_name = config['name']
        self.token_file = config['token-file']
        self.hours = config['hours']
        credentials = (self.client_id, self.secret_id)
        protocol = MSGraphProtocol()
        scopes = [
            'User.Read', 'Calendars.Read', 'Calendars.Read.Shared',
            'offline_access'
        ]
        self.account = Account(
            credentials,
            protocol=protocol,
            token_backend=FileSystemTokenBackend(token_path=self.token_file))
        if not self.account.is_authenticated:
            if self.account.authenticate(scopes=scopes):
                print('Authenticated!')
            else:
                print("Failed to authenticate")
        else:
            print("Skipping authentication because token already exists")

    def get_entries(self, hours: int = None) -> List[CalendarEntry]:
        if hours is None:
            hours = self.hours
        schedule = self.account.schedule()
        cal = schedule.get_calendar(calendar_name=self.calendar_name)
        if cal is None:
            calendars = [
                schedule.name for schedule in schedule.list_calendars()
            ]
            raise RuntimeError(
                f"Calendar '{self.calendar_name}' does not exist for current Outlook account. Avaiblable calendars are: {calendars}"
            )
        q = cal.new_query('start').greater_equal(datetime.datetime.now())
        q.chain('and').on_attribute('end').less_equal(datetime.datetime.now() +
                                                      datetime.timedelta(
                                                          hours=hours))
        events = cal.get_events(query=q, include_recurring=True)
        return [self.convert_entry(entry) for entry in events]

    @staticmethod
    def convert_entry(event: calendar.Event):
        return CalendarEntry(start=event.start,
                             length=event.end - event.start,
                             title=event.subject)
Ejemplo n.º 16
0
def get_o365_mail(emailfrom, start_date, end_date):
    scopes = ['basic', 'mailbox']
    token_backend = FileSystemTokenBackend(token_path='.', token_filename='o365_token.txt')
    account = Account(
        scopes=scopes,
        credentials=('8cccb04f-b409-4d04-888b-20321dcc14b7', secret_config.o365_secret),
        token_backend=token_backend
    )

    if not account.is_authenticated:  # will check if there is a token and has not expired
        # ask for a login
        # console based authentication See Authentication for other flows
        account.authenticate()

    if account.is_authenticated:
        account.connection.refresh_token()

    my_mailbox = account.mailbox()
    my_inbox = my_mailbox.inbox_folder()

    try:
        converted_start_date = datetime.strptime(start_date, '%Y-%m-%d')
        converted_end_date = datetime.strptime(end_date, '%Y-%m-%d')
    except Exception as e:
        print("Could not convert start_date or end_date into a datetime.datetime ")
        raise e

    inbox_query = my_mailbox.new_query().on_attribute("from").contains(emailfrom)
    inbox_query = inbox_query.chain("and").on_attribute("created_date_time").greater_equal(converted_start_date)
    inbox_query = inbox_query.chain("and").on_attribute("created_date_time").less_equal(converted_end_date)

    messages = list()
    for message in my_inbox.get_messages(download_attachments=True,
                                         query=inbox_query):
        messages.append(message)
    return messages


    print("hammertime")
Ejemplo n.º 17
0
def authenticate_account(mailbox=None, retries=0):
    """
    Authenticate an O365 account.
    """
    credentials = (current_app.config['O365_CLIENT_ID'], None)
    protocol = MSOffice365Protocol(api_version='beta')
    account = Account(
        credentials,
        protocol=protocol,
        tenant_id=current_app.config['O365_TENANT_ID'],
        main_resource=mailbox or current_app.config['MAILBOX'],
        request_retries=retries,
        token_backend=DatabaseTokenBackend()
    )

    if account.is_authenticated:
        current_app.logger.info('Account already authenticated.')
    else:
        current_app.logger.info('Account not yet authenticated.')
        account.authenticate(tenant_id=current_app.config['O365_TENANT_ID'],
                             scopes=current_app.config['O365_SCOPES'])
        current_app.logger.info('Authenticated successfully.')
    return account
Ejemplo n.º 18
0
def get_outlook_events(cfg, now, end):
    credential = (cfg['AZURE_APP_APPLICATION_ID'],
                  cfg['AZURE_APP_CLIENT_SECRET'])
    account = Account(credential)
    if not account.is_authenticated:
        account.authenticate(scopes=['basic', 'calendar_all'])
    schedule = account.schedule()
    calendar = schedule.get_default_calendar()

    q = calendar.new_query('start').greater_equal(now)
    q.chain('and').on_attribute('end').less_equal(end)
    events = calendar.get_events(limit=100, query=q, include_recurring=True)
    """
    # we can only get 25 events, so I will get every weeks
    now = dt.datetime.now().astimezone()
    events = []
    for i in range(WEEKS):
        end = now + dt.timedelta(weeks=1)
        q = calendar.new_query('start').greater_equal(now)
        q.chain('and').on_attribute('end').less_equal(end)
        now = end
        events = events + list(calendar.get_events(limit=100, query=q, include_recurring=True))
    """

    garoon_origin_events = {}
    outlook_events = {}
    for event in events:
        #print('Outlook ' + event.subject)
        if event.subject.startswith('GID:'):
            gidpair = event.subject.split()[0]
            garoon_id = gidpair.split(':')[1]
            garoon_origin_events[garoon_id] = event
            print('Outlook - Garoon Origin Event ' + event.subject)
        else:
            outlook_events[event.object_id] = event
            print('Outlook - Outlook Origin Event ' + event.subject)
    return calendar, garoon_origin_events, outlook_events
    def authenticate(self):
        credentials = (self.client_id, self.secret_id)
        protocol = MSGraphProtocol()
        account = Account(credentials, protocol=protocol)

        if account.is_authenticated:
            print("Token file exists!")
        else:
            authenticated = account.authenticate(scopes=SCOPES)
            if authenticated:
                print('Authenticated!')
            else:
                print('Failed to authenticate.')

        return account
Ejemplo n.º 20
0
def main():
    """
    認証を行う

    """
    config = Config()
    credentials = (config.client_id, config.client_secret)
    token_backend = \
        FileSystemTokenBackend(
            token_path=config.token_path,
            token_filename=config.token_file
        )
    account = Account(credentials, token_backend=token_backend)
    if account.authenticate(scopes=['basic', 'message_all']):
        print('Authenticated!')
Ejemplo n.º 21
0
    def _authenticate(self):
        token_backend = FileSystemTokenBackend(
            token_path=os.path.dirname(os.path.realpath(__file__)))
        connection = Connection(config.credentials,
                                scopes=['basic', 'Calendars.Read'],
                                token_backend=token_backend)
        connection.refresh_token()
        account = Account(config.credentials,
                          scopes=['basic', 'Calendars.Read'],
                          token_backend=token_backend)

        if not account.is_authenticated:
            if account.authenticate():
                print('Authenticated!')
            else:
                print('Authentication failed!')
                return
        self._schedule = account.schedule()
Ejemplo n.º 22
0
def get_account(tenant: str, client_id: str, client_secret: str, tenant_id: str, interactive: bool = False) -> Account:
    " Get O365 Account "
    credentials = (client_id, client_secret)
    token_backend = FileSystemTokenBackend(
        os.path.expanduser(os.environ.get(ENV_HOME) or HOME),
        token_filename=tenant_id + ".json",
    )
    account = Account(
        credentials,
        auth_flow_type="authorization",
        tenant_id=tenant_id,
        token_backend=token_backend,
    )
    if not account.is_authenticated:
        if account.con.auth_flow_type in ("authorization", "public") and not interactive:
            raise Exception("Please run 'spo configure' to authenticate")
        if account.authenticate(scopes=O365_SCOPES):
            print("Authenticated!")
    return account
Ejemplo n.º 23
0
def get_team(obj_name, credentials, host, site, token_filepath=None, io=None):
    """ Returns a Sharepoint site object
    :param str obj_name: a list name or a path to an excel file in sharepoint
    :param tuple credentials: a tuple with Office 365 client_id and client_secret
    :param str host: A sharepoint host like anatel365.sharepoint.com
    :param str site: a site's name or team's name
    :param str token_filepath: path where the Office 365 token is or will be stored.
    :param str io: path to where downloaded objects (list or excel file) will be stored.
    :return: a Sharepoint Site
    :rtype: Site
    """

    # obter o caracter de split do filepath
    split_char, to_path, name = get_path_name(obj_name=obj_name, io=io)

    # separar o token_filename do token_path
    if not token_filepath:
        token_filename = 'o365token.txt'
        token_path = to_path + split_char
    else:
        token_filename = token_filepath.split(split_char)[-1]
        token_path = split_char.join(
            token_filepath.split(split_char)[:-1]) + split_char

    # Obter o token
    token_backend = FileSystemTokenBackend(token_path=token_path,
                                           token_filename=token_filename)
    # criar o objeto account
    account = Account(credentials, token_backend=token_backend)
    # scope para sharepoint
    scopes = ['basic'] + MSGraphProtocol().get_scopes_for(
        user_provided_scopes='sharepoint')

    # Autenticação
    if not isfile(token_path + token_filename):
        if not account.authenticate(scopes=scopes):
            raise Exception(
                'Não foi possível autenticar com as credenciais e token informados'
            )

    sharepoint = account.sharepoint()
    team = sharepoint.get_site(host, 'sites/' + site)
    return team
Ejemplo n.º 24
0
class MyO365():
    def __init__(self, credentials):
        """
        credentials = ('dhasldl-b8ab-4730-93f1-cee730a4044b', 'salhdlghsaldh~ufOj2-4~69sCMZ05D_')
        """
        self.account = Account(credentials)
        ok = False
        if not self.account.is_authenticated:
            ok = self.account.authenticate(scopes=['basic', 'message_all'])
        else:
            ok = True
        if ok:
            print('Authenticated!')
        else:
            print('Not Authenticated!')
            raise Exception("Email sender not authenticated!")

    def send_email(self, receiver: str, subject: str, body: str):
        m = self.account.new_message()
        m.to.add(receiver)
        m.subject = subject
        m.body = body
        m.send()
Ejemplo n.º 25
0
from O365 import Account
from dotenv import load_dotenv
from O365.connection import MSGraphProtocol

load_dotenv()
CLIENT_ID = os.environ.get('EMAIL_ID')
CLIENT_SECRET = os.environ.get('EMAIL_SECRET')
TENANT_ID = os.environ.get('TENANT_ID')
SERVER_IP = os.environ.get('SERVER_IP')
EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS')

credentials = (CLIENT_ID, CLIENT_SECRET)
account = Account(credentials,
                  tenant_id=TENANT_ID,
                  auth_flow_type='credentials')
if account.authenticate(scopes=['https://graph.microsoft.com/.default']):

    while True:
        email, token = input().split()
        mailbox = account.mailbox(EMAIL_ADDRESS)
        m = mailbox.new_message()
        m.to.add(email)
        m.subject = 'Cyberhawks Email Confirmation Test!'
        m.body = """
                <html>
                    <body>
                        Please <a href=\"http://""" + str(
            SERVER_IP) + "/" + str(
                token
            ) + """\">follow this link</a> to confirm your discord account.</p>
                    </body>
Ejemplo n.º 26
0
from O365 import Account
credentials = ('id', 'secret')
scopes = [
    'https://graph.microsoft.com/Mail.ReadWrite',
    'https://graph.microsoft.com/Mail.Send'
]
account = Account(credentials, scopes=scopes)
account.authenticate()
m = account.new_message()
m.to.add('*****@*****.**')
m.subject = 'Testing!'
m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
m.send()
Ejemplo n.º 27
0
if not os.path.exists('auth'):
    print('auth directory does not exist.  Creating...')
    os.makedirs('auth')

c = json.loads(open('secret/secret.json').read())

parser = argparse.ArgumentParser(
    description=
    "Authenticate email via M365 OAuth2.0 authentication.  By Drew Sidman <*****@*****.**>"
)

#required arguments
req = parser.add_argument_group('Required arguments')
req.add_argument('-e',
                 '--email',
                 type=str,
                 metavar='',
                 required=True,
                 help='Email address')

args = parser.parse_args()

credentials = (c['client_id'], c['client_secret'])

token_backend = FileSystemTokenBackend(token_path='auth',
                                       token_filename=args.email)

account = Account(credentials, token_backend=token_backend)

if account.authenticate(scopes=['basic', 'message_all']):
    print('Authenticated!')
Ejemplo n.º 28
0
        if item.is_file:
            download_file(item, current_path)


def create_folder(item, current_path):
    folder = os.path.join(current_path, item.name)
    os.makedirs(folder, exist_ok=1)
    print(f"Dossier {item.name} créé avec succès !")
    return folder


def download_file(item, path):
    item.download(to_path=path, chunk_size=None)
    print(f"Fichier {item.name} téléchargé avec succès !")


protocol = MSGraphProtocol(api_version='beta')
credentials = ('7b9c81d7-2c01-4d48-86fc-9a7cd9700b85',
               'cBPj06Vjh_[HNkntI-e6pEf.h1JKn12H')

token_backend = FileSystemTokenBackend(token_path='my_folder',
                                       token_filename='my_token.txt')
account = Account(credentials, protocol=protocol, token_backend=token_backend)
account.authenticate(
    scopes=['basic', 'message_all', 'onedrive_all', 'address_book_all'])

storage = account.storage()
my_drive = storage.get_default_drive()

save_folder(my_drive)
Ejemplo n.º 29
0
def authenticate():
    account = Account(credentials=credentials, token_file_name=token_location)
    account.authenticate(scopes=scope_helpers)
Ejemplo n.º 30
0
class O365Account():
    def __init__(self,
                 client_id=client_id,
                 client_secret=client_secret,
                 scopes=scopes):
        self.client_id = client_id
        self.client_secret = client_secret
        self.account = Account(credentials=(client_id, client_secret))
        self.authenticate(scopes)

        self.storage = self.account.storage()
        self.drives = self.storage.get_drives()
        self.my_drive = self.storage.get_default_drive(
        )  # or get_drive('drive-id')
        self.root_folder = self.my_drive.get_root_folder()

    def authenticate(self, scopes=scopes):
        result = self.account.authenticate(scopes=scopes)

    def get_drive(self):
        return self.my_drive

    def get_root_folder(self):
        return self.root_folder

    def get_folder_from_path(self, folder_path):
        if folder_path is None:
            return self.my_drive

        subfolders = folder_path.split('/')
        if len(subfolders) == 0:
            return self.my_drive

        items = self.my_drive.get_items()
        for subfolder in subfolders:
            try:
                subfolder_drive = list(
                    filter(lambda x: subfolder in x.name, items))[0]
                items = subfolder_drive.get_items()
            except:
                raise ('Path {} not exist.'.format(folder_path))
        return subfolder_drive

    ''' Upload a file named $filename to onedrive folder named $destination. '''

    def upload_file(self, filename, destination=None):
        folder = self.get_child_folder(self.root_folder, destination)
        print('Uploading file ' + filename)
        folder.upload_file(item=filename)

    ''' Download a file named $filename to local folder named $to_path. '''

    def download_file(self, filename, to_path=None):
        dirname = os.path.dirname(filename)
        basename = os.path.basename(filename)
        folder = self.get_folder_from_path(dirname)
        items = folder.get_items()
        if not os.path.exists(to_path):
            os.makedirs(to_path)
        try:
            file = list(filter(lambda x: basename in x.name, items))[0]
            print('Downloading file ' + filename)
            file.download(to_path, chunk_size=CHUNK_SIZE)
            return True
        except:
            print('File {} not exist.'.format(filename))
            return False

    def _get_child_folder(self, folder, child_folder_name):
        items = folder.get_items()
        child_folder_names = [item.name for item in items if item.is_folder]
        if child_folder_name in child_folder_names:
            return list(filter(lambda x: x.name == child_folder_name,
                               items))[0]
        else:
            return folder.create_child_folder(child_folder_name)

    ''' Get child folder, folder tree from root folder. If child folder not exist, make it. '''

    def get_child_folder(self, folder, child_folder_name):
        child_folder_names = child_folder_name.split('/')
        for _child_folder_name in child_folder_names:
            folder = self._get_child_folder(folder, _child_folder_name)
        return folder

    '''
    Upload entire folder named $folder_name from local to onedrive folder named $destination.
    Keep cloud folder structure as that of local folder.
    '''

    def upload_folder(self, folder_name, destination=None):
        print()
        print('Uploading folder ' + folder_name)
        if destination is None:
            destination = folder_name
        destination_item = self.get_child_folder(self.root_folder, destination)

        for file in os.listdir(folder_name):
            path = os.path.join(folder_name, file)
            if os.path.isfile(path):
                self.upload_file(path, destination)
            else:
                folder = self.get_folder_from_path(destination)
                child_destination = self.get_child_folder(folder, file)
                self.upload_folder(path, os.path.join(destination, file))

    '''
    Download entire folder named $folder_name from cloud to local folder named $to_folder.
    Keep local folder structure as that of cloud folder.
    '''

    def download_folder(self, folder_name, to_folder='.', file_type=None):
        to_folder = os.path.join(to_folder, folder_name)
        self._download_folder(folder_name, to_folder, file_type)

    def _download_folder(self, folder_name, to_folder='.', file_type=None):
        print()
        print('Downloading folder ' + folder_name)
        current_wd = os.getcwd()
        if to_folder is not None and to_folder != '.':
            if not os.path.exists(to_folder):
                os.makedirs(to_folder)
            os.chdir(to_folder)

        if folder_name is None:
            folder = self.get_drive()
        folder = self.get_folder_from_path(folder_name)

        items = folder.get_items()
        if file_type is None:
            file_type = ''
        files = list(
            filter(lambda x: file_type in x.name or x.is_folder, items))

        for file in files:
            file_name = file.name
            abs_path = os.path.join(folder_name, file_name)
            if file.is_file:
                print('Downloading file ' + abs_path)
                file.download(chunk_size=CHUNK_SIZE)
            else:
                child_folder_name = abs_path
                self._download_folder(child_folder_name, file_name, file_type)
        os.chdir(current_wd)