Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.46 KB | None | 0 0
  1. from __future__ import print_function
  2. from apiclient.discovery import build
  3. from httplib2 import Http
  4. from oauth2client import file, client, tools
  5. from docx import Document
  6. import sys
  7. import re
  8. import requests
  9. import datetime
  10.  
  11. path = "/home/zander/Downloads/Sommerferieplan-2018.docx"
  12. doc = Document(path)
  13. name = "malene"
  14. tables = doc.tables
  15.  
  16. def readTable(table):
  17.     w = False
  18.     typ = table.rows[0].cells[0].paragraphs[0].text.lower().strip()
  19.     if 'aften' not in typ and 'weekender' not in typ and 'dag' != typ:
  20.         return [], None
  21.  
  22.     if typ == 'weekender':
  23.         w = True
  24.     weeks = [x.cells[0].paragraphs[0].text for x in table.rows][1:]
  25.     weeks = [re.match(".*\s(\d+)", x)[1] for x in weeks]
  26.     weeks = [int(x) for x in weeks]
  27.  
  28.     mIndex = []
  29.     i = 0
  30.     j = 0
  31.     for row in table.rows:
  32.         j = 0
  33.         for cell in row.cells:
  34.             for p in cell.paragraphs:
  35.                 if p.text.lower() == name:
  36.                     mIndex.append((i-1,j-1))
  37.             j += 1
  38.         i += 1
  39.  
  40.     if w:
  41.         return [weeks[x[0]] for x in mIndex], typ
  42.  
  43.     row = table.rows[0]
  44.     times = [x.paragraphs[0].text for x in row.cells][1:]
  45.     times = [re.match('.*?(\d+)-(\d+).*', x) for x in times]
  46.     times = [(int(x[1]), int(x[2])) for x in times]
  47.  
  48.     return [(weeks[x[0]], times[x[1]]) for x in mIndex], typ
  49.  
  50. def dayToDate(h, d, w, year=2018):
  51.     d = d + 1
  52.     d = d % 7
  53.     time = str(h).zfill(2) + ":" + str(0).zfill(2)
  54.     date = datetime.datetime.strptime(str(year)+"-W" + str(w)+"-" + str(d) + "-" + time, "%Y-W%W-%w-%H:%M")
  55.     return date
  56.  
  57. def DayToStartEnd(tup, d):
  58.     startW, time = tup
  59.     endW = startW
  60.     startH, endH = time
  61.     startD = d
  62.     endD = d+1 if (endH <= startH) else d
  63.     if endD == 7:
  64.         d = 0
  65.         endW += 1
  66.     start = dayToDate(startH, startD, startW)
  67.     end = dayToDate(endH, endD, endW)
  68.     return (start,end)
  69.    
  70. def dayTupToSpan(tup):
  71.     return [DayToStartEnd(tup, d) for d in range(0, 5)]
  72.  
  73. def nightTupToSpan(tup):
  74.     return [DayToStartEnd(tup, d) for d in range(0, 4)]
  75.  
  76. def weekToSpan(w):
  77.     return [
  78.         DayToStartEnd((w, (12, 20)), 4),
  79.         DayToStartEnd((w, (9, 19)), 5),
  80.         DayToStartEnd((w, (9, 17)), 6)
  81.     ]
  82.  
  83.  
  84. def tableToSpan(table):
  85.     tups, typ = readTable(table)
  86.     if typ is None:
  87.         return []
  88.     if "dag" in typ:
  89.         f = dayTupToSpan
  90.     if "aften" in typ:
  91.         f = nightTupToSpan
  92.     if "week" in typ:
  93.         f = weekToSpan
  94.     arr = [f(tup) for tup in tups]
  95.     return sum(arr, [])
  96.  
  97. spans = sum([tableToSpan(x) for x in tables], [])
  98. spans = sorted(spans)
  99.  
  100. def merge_date_ranges(data):
  101.     result = []
  102.     t_old = data[0]
  103.     for t in data[1:]:
  104.         if t_old[1] >= t[0]:  #I assume that the data is sorted already
  105.             t_old = ((min(t_old[0], t[0]), max(t_old[1], t[1])))
  106.         else:
  107.             result.append(t_old)
  108.             t_old = t
  109.     else:
  110.         result.append(t_old)
  111.     return result
  112.  
  113. spans = merge_date_ranges(spans)
  114.  
  115. def spanToEvent(tup):
  116.     s,e = tup
  117.     return {
  118.         'summary': 'Arbejde',
  119.         'location': 'VBM Laboratoriet A/S - Industrivej 1, 9440 Aabybro',
  120.         'start': {
  121.             'dateTime': s.isoformat('T'),
  122.             'timeZone': 'Europe/Copenhagen'
  123.         },
  124.         'end': {
  125.             'dateTime': e.isoformat('T'),
  126.             'timeZone': 'Europe/Copenhagen'
  127.         },
  128.         'reminders': {
  129.             'useDefault': False
  130.         }
  131.     }
  132.  
  133. events = [spanToEvent(x) for x in spans]
  134.  
  135. # Setup the Calendar API
  136. SCOPES = 'https://www.googleapis.com/auth/calendar'
  137. store = file.Storage('credentials.json')
  138. creds = store.get()
  139. if not creds or creds.invalid:
  140.     flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
  141.     creds = tools.run_flow(flow, store)
  142. service = build('calendar', 'v3', http=creds.authorize(Http()))
  143.  
  144. calendarId = None
  145. for cal in service.calendarList().list().execute()['items']:
  146.     if 'malene' in cal['summary'].lower() and 'arbejde' in cal['summary'].lower():
  147.         calendarId = cal['id']
  148. if calendarId is None:
  149.     calendar = {
  150.         'summary': 'Malene - Arbejde',
  151.         'timeZone': 'Europe/Copenhagen'
  152.     }
  153.     created_calendar = service.calendars().insert(body=calendar).execute()
  154.     calendarId = created_calendar['id']
  155.  
  156. def addEvent(calId, event):
  157.     service.events().insert(calendarId=calId, body=event).execute()
  158.  
  159. for e in events:
  160.     addEvent(calendarId, e)
  161.  
  162. print("tilføjet :-)")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement