Browse Source

Changed the script to be better for inline config and running from the commandline.

Also improved the readme and documentation.
master
Roxie Gibson 4 years ago
parent
commit
6fa69a424b
No known key found for this signature in database
3 changed files with 82 additions and 24 deletions
  1. +43
    -5
      readme.md
  2. +33
    -18
      seatingplan/__main__.py
  3. +6
    -1
      setup.py

+ 43
- 5
readme.md View File

@@ -1,15 +1,53 @@

# Seating Plan Generator

Script to generate a seating plan via calendar events in an organsations Office365.
Script to generate a seating plan via calendar events in an organsation's Office365.

## What it does

The script looks at the current week and generates a seating plan for that week. **Note** Current week is defined during the normal work weeks. If the script is ran on the weekend (Saturday and Sunday) the script will generate next weeks and label it as such.
The script looks at the current week and generates a seating plan for that week. It will then create a csv to represent this. This is done using the default calendar of the user who allows the script access to their account. **Note** Current week is defined during the normal work weeks. If the script is ran on the weekend (Saturday and Sunday) the script will generate next weeks and label it as such.

## Installation
## Pre-Install

TO BE WRITTEN
To setup the script, you will need to create an app in your organisation Azure Active Directory. You can find the app registration page [here](hhttps://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps).

For a guide on how to do this, see the guide provided by python-o365 below.

**MAKE SURE TO READ OVER THIS BEFORE SENDING TO CLIENT**
>To work with oauth you first need to register your application at [Azure App Registrations](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade).

> 1. Login at [Azure Portal (App Registrations)](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade)
> 1. Create an app. Set a name.
> 1. In Supported account types choose "Accounts in any organizational directory.
> 1. Set the redirect uri (Web) to: `https://login.microsoftonline.com/common/oauth2/nativeclient` and click register. This is the default redirect uri used by this library, but you can use any other if you want.
> 1. Write down the Application (client) ID AND Directory (tenant) ID. You will need these values.
> 1. Under "Certificates & secrets", generate a new client secret. Set the expiration preferably to never.
> 1. Write down the value of the client secret created now. It will be hidden later on.
> 1. Under Api Permissions add the delegated permissions for Microsoft Graph you want


The required Api Permissions are:

```
Calendars.Read.Shared
User.Read
User.ReadBasic.All
offline_access
```

Once the app has been created, git clone this repo, cd into it's folder and install it into your user's Python PATH.

```sh
git clone URL
cd seatplangen
python3 -m pip install . --user
```

Once installed, you can run the script like this.

```sh
seatingplan -c "CLIENT-ID" -t "TENANT-ID" -s "CLIENT-SECRET"
```

The first time the script is ran, it will ask you to visit a url. Open the url in your browser and allow the script access to the requested permissions. Once you have done that, you will be redirected to a blank page. Copy the URL and paste it into the console and press enter. **Note** You should give access **AS** the account who's calendar is being used to store who's out of office.

This will only need to be done every 90 days.

+ 33
- 18
seatingplan/__main__.py View File

@@ -1,7 +1,19 @@
#!/usr/bin/env python3


from O365 import Account, MSOffice365Protocol, FileSystemTokenBackend, Connection
import configparser
from datetime import datetime, timedelta
import argparse


parser = argparse.ArgumentParser(prog='seatingplan', description="Script to generate a seating plan via Office365 Calendars")
parser.add_argument("-c", "--client-id", type=str, required=True, dest='client_id',
help='Client ID for registered azure application')
parser.add_argument("-s", "--client-secret", type=str, required=True, dest='client_secret',
help='Client secret for registered azure application')
parser.add_argument("-t", "--tenant-id", type=str, required=True, dest='tenant_id',
help='Tenant ID for registered azure application')


def read_config():
@@ -9,26 +21,33 @@ def read_config():
Reads config file and sets up variables foo
:return: credentials: ('client_id', 'client_secret') and tenant: str
"""
# TODO: Deprecate this file so we use an arg version instead
config = configparser.ConfigParser()
config.read("./config")

credentials = (config["client"]["id"], config["client"]["secret"])
tenant = config["client"]["tenant"]
email = config["client"]["out_of_office_email"]

return credentials, tenant
return credentials, tenant, email


def create_session():
"""
Create a session with the API and save the token for later use.
:return: Account class
:return: Account class and email: str
"""
credentials, tenant = read_config()
my_protocol = MSOffice365Protocol(api_version='v2.0')
config = parser.parse_args()
credentials = (config.client_id, config.client_secret)
tenant = config.tenant_id
my_protocol = MSOffice365Protocol(api_version='v2.0')
token_backend = FileSystemTokenBackend(token_filename='access_token.txt')
return Account(credentials, protocol=my_protocol, tenant_id=tenant,
token_backend=token_backend) # the default protocol will be Microsoft Graph

return Account(
credentials,
protocol=my_protocol,
tenant_id=tenant,
token_backend=token_backend
)

def authenticate_session(session: Account):
"""
@@ -63,7 +82,7 @@ def get_week_datetime():
"""
Gets the current week's Monday and Friday to be used to filter a calendar.

If this script is ran during the week, it will be the current week. If it is ran on the weekend, it will generate for next week.
If this script is ran during the work week (Monday-Friday), it will be the current week. If it is ran on the weekend, it will generate for next week.
:return: Monday and Friday: Datetime object
"""
today = datetime.now()
@@ -88,25 +107,21 @@ def main():
session = create_session()
authenticate_session(session)

r = oauth_request(session.con, "https://outlook.office.com/api/v2.0/users/EMAIL/")
r = session.con.oauth_request("https://outlook.office.com/api/v2.0/users/{email}/calendar/events", "get")

# request = account.con.oauth_request("https://outlook.office.com/api/v2.0/users/EMAIL/calendar/events?$filter=Start/DateTime ge '2019-09-04T08:00' AND End/Datetime le '2019-09-05T08:00'&$top=50", "get")
print(r.text)

# setup csv
# For loop over all emails
# API request for user info of email
# Get display name
# API request for events this week
# Find sign of being in or not being in
# insert name in csv for the days they are in and at what seat (if regular)
# API request events from out of office email
# loop over events
# find out who the event is talking about
# insert into csv
# output csv


monday, friday = get_week_datetime()
print(f"Monday is {monday}, Friday is {friday}")




if __name__ == "__main__":
main()

+ 6
- 1
setup.py View File

@@ -2,12 +2,17 @@ import setuptools

# TODO: This needs to generate a config and make sure it is installed

LONG_DESC = open('readme.md').read()

setuptools.setup(
name="Seating Plan Generator",
author="Roxanne Gibson",
author_email="me@roxanne.dev",
description="Script to generate a seating plan via Office365 Calendars",
long_description_content_type="text/markdown",
long_description=LONG_DESC,
packages=["seatingplan"],
entry_points={"console_scripts": ["seatingplan=seatingplan.__main__:main"]},
python_requires=">=3.5",
)
install_requires=("o365==2.0.1")
)

Loading…
Cancel
Save