Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import smtplib
- import re
- import os
- from datetime import datetime
- from jinja2 import Environment, FileSystemLoader
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- log_path = os.path.expanduser('~/unison.log')
- error_log_path = os.path.expanduser('~/unison_error.log')
- directory_path = os.path.expanduser('~')
- emails = lambda _: _
- emails.gmail = lambda _: _
- emails.gmail.username = 'canada.sync.log@gmail.com'
- emails.gmail.password = 'canadacanada'
- emails.receipients = [
- 'gallery@canadanewyork.com',
- ]
- origins = {'//server.canada.private//Volumes/Gallery Data': 'Gallery',
- '/Volumes/Clone of Gallery Data/gallery clone': 'Amherst'}
- def analyze_log(log):
- data = lambda _: _
- data.date_time = {}
- data.items = []
- for line in log:
- data = analyze_line(line, data)
- send_email(data)
- class item(object):
- def __init__(self, file_location, operation, origin=None, destination=None):
- self.origins = origins.copy()
- self.file_location = file_location
- self.operation = operation
- if origin:
- self.origin = self.origins[origin]
- self.origins.pop(origin)
- self.destination = self.origins.values()[0]
- elif destination:
- self.destination = self.origins[destination]
- self.origins.pop(destination)
- self.origin = self.origins.values()[0]
- def analyze_line(line, data):
- transfer = re.match(r"""
- \[BGN\][ ]
- (?P<operation>[a-zA-Z ]+?)[ ]
- (?P<file_location>((?!file[ ]).)+?) #Not starting with ' file'
- [ ]from[ ]
- (?P<origin>({0}|{1}))(([ ]to[ ]({0}|{1}))|$)
- """.format(*(re.escape(key) for key in origins.keys())), line, re.VERBOSE)
- date_time = re.match(r"""
- UNISON[ ][0-9.]+[ ]
- (?P<location>[a-z]+)[a-z ]+
- (?P<date_time>.+)
- """, line, re.VERBOSE)
- failed = re.match(r' failed: (?P<file_location>.+)', line)
- conflict = re.match(r'\[CONFLICT\] Skipping (?P<file_location>.+)', line)
- if transfer:
- transfer_dict = transfer.groupdict()
- operations = {'Copying': 'Copied',
- 'Deleting': 'Deleted',
- 'Updating file': 'Updated',
- }
- transfer_dict['operation'] = operations[transfer_dict['operation']]
- if transfer.group('operation') == 'Deleting':
- transfer_dict['destination'] = transfer_dict.pop('origin')
- data.items.append(item(**transfer_dict))
- elif failed:
- failed_dict = failed.groupdict()
- data = remove_file_record(data, failed_dict['file_location'])
- data.items.append(item(operation='Failed', **failed_dict))
- elif conflict:
- conflict_dict = conflict.groupdict()
- data = remove_file_record(data, conflict_dict['file_location'])
- data.items.append(item(operation='Conflict', **conflict_dict))
- elif date_time:
- date_time = date_time.groupdict()
- data.date_time[date_time['location']] = date_time['date_time']
- return data
- def remove_file_record(data, file_location):
- [data.items.remove(item) for item in data.items if item.file_location == file_location]
- return data
- def send_email(data):
- msg = MIMEMultipart('alternative')
- msg['Subject'] = 'Completed: {} items synced'.format(len(data.items))
- msg['From'] = emails.gmail.username
- msg['To'] = ', '.join(emails.receipients)
- text, html = compile_email(data)
- part1 = MIMEText(text, 'plain')
- part2 = MIMEText(html, 'html')
- msg.attach(part1)
- msg.attach(part2)
- server = smtplib.SMTP('smtp.gmail.com', 587)
- server.ehlo()
- server.starttls()
- server.ehlo()
- server.login(emails.gmail.username, emails.gmail.password)
- server.sendmail(msg['From'], emails.receipients, msg.as_string())
- server.quit()
- def compile_email(data):
- loader = FileSystemLoader(directory_path)
- env = Environment(trim_blocks=True, loader=loader)
- env.globals['time_diff'] = time_diff
- context = {
- 'items': sorted(data.items, key=lambda item: item.file_location),
- 'time_diff': time_diff(**data.date_time),
- }
- html = env.get_template('sync.html').render(**context)
- text = env.get_template('sync.txt').render(**context)
- return text, html
- def time_diff(started=None, finished=None):
- if (started or finished) == None:
- return None
- format = '%H:%M:%S.%f on %d %b %Y'
- start = datetime.strptime(started, format)
- finish = datetime.strptime(finished, format)
- return str(finish - start)
- def run():
- try:
- log = open(log_path)
- except IOError:
- log = ''
- analyze_log(log)
- else:
- analyze_log(log)
- os.rename(log_path, log_path + '.old')
- log.close()
- run()
Add Comment
Please, Sign In to add comment