def update_meetings(res, start_time, subject, URL, USERNAME, PASSWORD):
    if res == "ok":
        print("ok")
        # Set up the connection to Exchange
        connection = ExchangeNTLMAuthConnection(url=URL,
                                                username=USERNAME,
                                                password=PASSWORD)

        service = Exchange2010Service(connection)
        events = service.calendar().list_events(
            start=timezone("US/Pacific").localize(
                datetime(2018, 11, 5, 7, 0, 0)),
            end=timezone("US/Pacific").localize(datetime(2018, 11, 7, 4, 0,
                                                         0)),
            details=True,
            delegate_for=None)

        for events in events.events:
            if str(events.start) == '2018-11-06 00:00:00+00:00':
                # print ("------\n Object Type = {type_events}\n start_time = {start}\n end_time = {stop} \n Subject = {subject} \n Organizer = {organiser}\n events_id = {events_id}\n--------------".format(
                #     start=events.start,
                #     stop=events.end,
                #     subject=events.subject,
                #     organiser = events.organizer.email,
                #     type_events = type(events),
                #     events_id = events.id
                # ))
                new_start = events.start + timedelta(minutes=10)
                events.start = new_start
                events.update()
                print('Completed Updating the meeting')

    else:
        print("Not Updating the meeting")
def list_meetings_and_save_in_DB(room_name):
    ###credentials for outlook exchange:
    URL = u'https://mail.cisco.com/ews/exchange.asmx'
    USERNAME = u'jgerardf'
    PASSWORD = u"Abcd$127"

    # Set up the connection to Exchange
    connection = ExchangeNTLMAuthConnection(url=URL,
                                            username=USERNAME,
                                            password=PASSWORD)

    service = Exchange2010Service(connection)

    val = u'{}'.format(room_name)

    print(room_name, val)
    events = service.calendar().list_events(
        start=timezone("US/Pacific").localize(datetime(2018, 11, 8, 7, 0, 0)),
        end=timezone("US/Pacific").localize(datetime(2018, 11, 10, 7, 0, 0)),
        details=True,
        delegate_for=val)
    truncate_query = "TRUNCATE TABLE outlook_meetings"

    mysql_connection(truncate_query)

    for events in events.events:
        insert_query = "INSERT INTO outlook_meetings(event_id,event_subject,event_organizer,event_start,event_end,event_start_utc,event_end_utc) VALUES('{}','{}','{}','{}','{}','{}','{}')".format(
            events.id, events.subject, events.organizer.email,
            convert_to_pacific(events.start), convert_to_pacific(events.end),
            events.start, events.end)

        #print(insert_query)

        mysql_connection(
            insert_query)  ##calling to insert meetings info into DB
示例#3
0
    def ews_connection(self):
        '''This connection for sending the meeting invite, which don't support by exchangelib'''
        if not self._ews_connection:
            configuration = ExchangeNTLMAuthConnection(url=self.url,
                                                       username=self.username,
                                                       password=self.password)
            self._ews_connection = Exchange2010Service(configuration)

        return self._ews_connection
示例#4
0
    def __init__(self, domain, url, username, password, timezone):
        super(ExchangeCalendar, self).__init__()

        self.timezone = timezone

        connection = ExchangeNTLMAuthConnection(url=url,
                                                username='******' %
                                                (domain, username),
                                                password=password)
        self._service = Exchange2010Service(connection)
        self.calendar = self._service.calendar()
示例#5
0
    def initialize(self):
        """
        Initialize connection and schedule periodic events.
        """
        # Loading optional modules only when module is configured.
        from pyexchange import Exchange2010Service
        from pyexchange import ExchangeNTLMAuthConnection

        self.connection = ExchangeNTLMAuthConnection(url=self.url,
                                                     username=self.username,
                                                     password=self.password)
        self.service = Exchange2010Service(self.connection)
        self.exch_calendar = self.service.calendar()
        self.connection.build_session()

        if self.ca_path is not None:
            self.connection.session.verify = self.ca_path

        # Initial refresh
        self.refresh_events()
        self.scheduler.every(60 * 10).seconds.do(self.refresh_events)
def get_calendar_events_cocus():
    URL = u'https://smtp.sfp-net.com/EWS/Exchange.asmx'
    USERNAME = config.outlook_username
    PASSWORD = read_password()

    # Set up the connection to Exchange
    connection = ExchangeNTLMAuthConnection(url=URL,
                                            username=USERNAME,
                                            password=PASSWORD)

    service = Exchange2010Service(connection)

    my_calendar = service.calendar()

    start = datetime.combine(date.today(), time.min)
    end = datetime.combine(date.today(), time.max)

    events = my_calendar.list_events(start, end)
    # details = events.load_all_details()

    event_list = []
    if events:
        for event in events.events:

            event_date = event.start.date().isoformat()
            event_start_time = (event.start + timedelta(hours=1)).time().isoformat()
            event_end_time = (event.end + timedelta(hours=1)).time().isoformat()

            # if 'Nao' in event.subject and 'Home' in event.subject:
            #    print('Maybe found do not use home office')
            #    print('Event %s on %s. From %s until %s' %
            #          (event.subject, event_date, event_start_time, event_end_time))
            #    continue  # ignore event

            print('Event %s on %s. From %s until %s' % (event.subject, event_date, event_start_time, event_end_time))
            now = datetime.now(timezone.utc) + timedelta(hours=1)
            print(now)

            if event.start + timedelta(hours=1) <= now <= event.end + timedelta(hours=1):
                is_happening_now = True
            else:
                is_happening_now = False

            # events_filtered += filter_out_events(event)
            if is_happening_now:
                event_list += filter_out_events(event)

    event_list = event_list[0] if event_list else False

    return event_list
示例#7
0
    def _get_service(self, username, password):
        """
        Get the calendar for the given connection
        """
        connection = ExchangeNTLMAuthConnection(
            url=self.asmx_url,
            username='******'.format(
                domain=self.domain,
                username=username,
            ),
            password=password)

        service = Exchange2010Service(connection)

        return service
示例#8
0
def get_events_from_exchange():
    conf = config['Exchange']
    verify_cert = conf.getboolean('VerifyCert', True)

    # Disable SSL warnings when certification verification is turned off
    if not verify_cert:
        requests.packages.urllib3.disable_warnings()

    decrypted_password = base64.b64decode(conf['Password']).decode('utf-8')
    connection = ExchangeNTLMAuthConnection(url=conf['URL'],
                                            username=conf['Username'],
                                            password=decrypted_password,
                                            verify_certificate=verify_cert)
    service = Exchange2010Service(connection)
    calendar = service.calendar()

    return calendar.list_events(start=start_date, end=end_date, details=True)
示例#9
0
文件: bot.py 项目: r-soc/ergigit
def give_events(message):
    # Set up the connection to Exchange
    from pyexchange import Exchange2010Service, ExchangeNTLMAuthConnection

    connection = ExchangeNTLMAuthConnection(url=config.ExchangeUrl,
                                            username=config.ExchangeUsername,
                                            password=config.ExchangePassword)

    try:
        service = Exchange2010Service(connection)

        curday = datetime.datetime.now()
        events = my_calendar.list_events(curday, curday)
        events.load_all_details()
        bot.send_message(message.chat.id,
                         events.load_all_details(),
                         parse_mode="Markdown")
    except LookupError:
        bot.send_message(message.chat.id,
                         "Не удалост прочитать Календарь",
                         parse_mode="Markdown")
def update_meetings(res, start_time, subject, URL, USERNAME, PASSWORD):
    if res == "ok":
        print("ok")
        # Set up the connection to Exchange
        connection = ExchangeNTLMAuthConnection(url=URL,
                                                username=USERNAME,
                                                password=PASSWORD)

        service = Exchange2010Service(connection)
        events = service.calendar().list_events(
            start=timezone("US/Pacific").localize(
                datetime(2018, 11, 8, 7, 0, 0)),
            end=timezone("US/Pacific").localize(datetime(
                2018, 11, 10, 7, 0, 0)),
            details=True,
            delegate_for=None)

        for events in events.events:
            #print(events.start)
            if str(events.start) == start_time:
                print(
                    "------\n Object Type = {type_events}\n start_time = {start}\n end_time = {stop} \n Subject = {subject} \n Organizer = {organiser}\n events_id = {events_id}\n--------------"
                    .format(start=events.start,
                            stop=events.end,
                            subject=events.subject,
                            organiser=events.organizer.email,
                            type_events=type(events),
                            events_id=events.id))
                # new_start = events.start+timedelta(minutes=10)
                # events.start = new_start
                # events.update()
                # print('Completed Updating the meeting')
            # else:
            #     #print('time did not match to find the required calendar object')

    else:
        print("Not Updating the meeting")
示例#11
0
def main(argv):
    try:
        opts, args = getopt.getopt(argv, "h:u:", ["host=", "user="******"-h", "--host"):
            host = a
        elif o in ("-u", "--user"):
            user = a

    pwd = getpass.getpass("Password for your outlook/exchange account: ")
    if not pwd:
        print 'You need to set the password!'
        sys.exit(2)

    connection = ExchangeNTLMAuthConnection(url=host,
                                            username=user,
                                            password=pwd)
    service = Exchange2010Service(connection)

    today = datetime.today()
    nextWeek = today + timedelta(days=7)

    events = service.calendar().list_events(start=today, end=nextWeek)

    for event in events.events:
        print "{start} {stop} - {subject}".format(start=event.start,
                                                  stop=event.end,
                                                  subject=event.subject)

    sys.exit(0)
示例#12
0

if __name__ == '__main__':

    try:
        mode = sys.argv[1]
    except IndexError:
        mode = 'normal'

    URL = 'https://mymail.qualcomm.com/EWS/Exchange.asmx'
    USERNAME = r'NA\jsmiller'
    PASSWORD = get_password()

    # Set up the connection to Exchange
    connection = ExchangeNTLMAuthConnection(url=URL,
                                            username=USERNAME,
                                            password=PASSWORD)

    service = Exchange2010Service(connection)

    my_calendar = service.calendar()

    local_tz = pytz.timezone("US/Pacific")

    now = datetime.now()
    this_morning = datetime(now.year, now.month, now.day, 0, 1, 0)
    this_evening = datetime(now.year, now.month, now.day, 23, 59, 0)
    with stderr_off():
        events = my_calendar.list_events(
            start=local_tz.localize(this_morning).astimezone(pytz.utc),
            end=local_tz.localize(this_evening).astimezone(pytz.utc),
示例#13
0
 def connect(self, username, password):
     self.connection = ExchangeNTLMAuthConnection(url=OUTLOOK_URL, username=username, password=password)
     self.service = Exchange2010Service(self.connection)
示例#14
0
class ExchPlugin(AssistantPlugin):
    """
    Exchange calendar integration. Reads events for today and in the given
    horizon and feeds them into the calendar core plugin.

    Will handle notifications and todays agenda display.
    """
    def validate_config(self):
        "Get all config values and test optional module existence."
        # Load optional modules only when module is configured.
        # Test here early that they exists.
        try:
            # pylint: disable=unused-variable
            from pyexchange import Exchange2010Service
            from pyexchange import ExchangeNTLMAuthConnection
        except ImportError:
            msg = ("Exchange Plugin requires an optional pyexchange module. "
                   "Install it with pip3 install pyexchange.")
            raise ConfigError(msg)

        self.username = self.config.get('username', assert_type=str)
        self.password = self.config.get('password', assert_type=str)
        self.url = self.config.get('url', assert_type=str)
        self.ca_path = self.config.get_path('ca_path', required=False)

        self.horizon_incoming = self.config.get('horizon_incoming',
                                                default=24,
                                                assert_type=int)

        self.my_email = self.config.get('my_email',
                                        default='',
                                        assert_type=str)

    def register(self):
        "Register commands"
        commands = [
            (['exch.refresh'], self.handle_refresh),
        ]
        for aliases, callback in commands:
            self.assistant.command.register(aliases, callback)

    def initialize(self):
        """
        Initialize connection and schedule periodic events.
        """
        # Loading optional modules only when module is configured.
        from pyexchange import Exchange2010Service
        from pyexchange import ExchangeNTLMAuthConnection

        self.connection = ExchangeNTLMAuthConnection(url=self.url,
                                                     username=self.username,
                                                     password=self.password)
        self.service = Exchange2010Service(self.connection)
        self.exch_calendar = self.service.calendar()
        self.connection.build_session()

        if self.ca_path is not None:
            self.connection.session.verify = self.ca_path

        # Initial refresh
        self.refresh_events()
        self.scheduler.every(60 * 10).seconds.do(self.refresh_events)

    def handle_refresh(self, message):
        "Handle force-refreshing and return stats on events"
        events = self.refresh_events()
        reply = "Read %d events from your calendar." % (len(events))
        message.respond(reply)

    def convert_event(self, exch_event):
        "Convert Exchange event to orgassist calendar event"
        # Drop external objects, gather all required data.
        # Don't leak abstraction.
        ctx = {
            'subject':
            exch_event.subject,
            'text_body':
            exch_event.text_body,
            'location':
            exch_event.location,
            'date_start':
            self.time.normalize(exch_event.start),
            'date_end':
            self.time.normalize(exch_event.end),
            'date_all_day':
            exch_event.is_all_day,
            'organizer':
            Attendee(name=exch_event.organizer.name,
                     email=exch_event.organizer.email,
                     required=True) if exch_event.organizer else None,
            'attendees': [
                Attendee(name=a.name, email=a.email, required=a.required)
                for a in exch_event.attendees if a is not None
            ],
            'your_meeting':
            False,
            'you_required':
            False,
        }

        # Safely determine organizer
        if ctx['organizer'] is None:
            ctx['organizer'] = Attendee(name='unknown',
                                        email='none',
                                        required=True)

        if ctx['organizer'].email == self.my_email:
            ctx['your_meeting'] = True

        myself = [a for a in ctx['attendees'] if a.email == self.my_email]

        if myself and myself[0].required:
            ctx['you_required'] = True

        # Context ready - construct our event
        parts = []
        if ctx['location']:
            parts.append('[' + ctx['location'] + ']')

        priority = 'C'
        if ctx['your_meeting']:
            parts.append('Your meeting')
            priority = 'A'
        elif ctx['you_required']:
            parts.append("Required by %s for" % ctx['organizer'].name)
            priority = 'B'
        elif not ctx['you_required']:
            parts.append("Informed by %s about" % ctx['organizer'].name)

        parts.append('"' + ctx['subject'] + '"')
        parts.append("(%d attending)" % len(ctx['attendees']))

        headline = " ".join(parts)

        event = Event(headline)
        event.priority = priority

        event.body = ctx['text_body']
        event.meta['exch'] = ctx

        date = EventDate((ctx['date_start'], ctx['date_end']), DateType.RANGE)
        event.add_date(date)

        return event

    def refresh_events(self):
        """
        Read events from exchange, convert and update calendar.
        """
        log.info("Periodic operation executed")

        now = self.time.now()

        start_of_day = now.replace(hour=0, minute=0)
        horizon_end = now + dt.timedelta(hours=self.horizon_incoming)

        try:
            events = self.exch_calendar.list_events(start=start_of_day,
                                                    end=horizon_end,
                                                    details=True)
        except AttributeError:
            # Module is badly written. In case of connection errors it
            # throws Attribute Error. Show error in case something weird
            # happened, but don't kill bot.
            log.exception("Connection (probably) error within exch module.")
            return None

        calendar_events = []
        for event in events.events:
            converted = self.convert_event(event)
            calendar_events.append(converted)

        log.info('Read %d events from exchange', len(calendar_events))

        # Use shared state to talk to core plugins
        self.state['calendar'].update_events(calendar_events, 'exch')
        return calendar_events
def connectEx():
    global exconnection, service
    exconnection = ExchangeNTLMAuthConnection(url=EX_URL,
                                              username=EX_USERNAME,
                                              password=EX_PASSWORD)
    service = Exchange2010Service(exconnection)
示例#16
0
from datetime import datetime
from pytz import timezone
from pyexchange import Exchange2010Service, ExchangeNTLMAuthConnection
from Event import Event

originURL = u'https://nomeDoServidor.outlook.com/EWS/Exchange.asmx'
originUsername = u'nomeDoUsuario'
originPassword = u"passwordDoUsuario"

# Set up the connection to Exchange
originConnection = ExchangeNTLMAuthConnection(url=originURL,
                                        username=originUsername,
                                        password=originPassword)

originService = Exchange2010Service(originConnection)

originCalendar = originService.calendar()

originEvents = originCalendar.list_events(
    start=timezone("America/Sao_Paulo").localize(datetime(2017, 11, 1, 0, 0, 0)),
    end=timezone("America/Sao_Paulo").localize(datetime(2017, 11, 17, 0, 0, 0)),
    details=True
)


destinyURL = u'https://outroServidor.outlook.com/EWS/Exchange.asmx'
destinyUsername = u'nomeUsuario'
originPassword = u'passwordUsuario'

# Set up the connection to Exchange
destinyConnection = ExchangeNTLMAuthConnection(url=destinyURL,
示例#17
0
import keyring
from pytz import timezone
from datetime import datetime
from pyexchange import Exchange2010Service, ExchangeNTLMAuthConnection
import json

credentials = json.load(open('calendarid.json'))

USERNAME = credentials["exchange"][0]["email"]
PASSWORD = keyring.get_password("ExchangeCalShopDirect", USERNAME)
URL = credentials["exchange"][0]["URL"]

print(PASSWORD)
# Set up the connection to Exchange
connection = ExchangeNTLMAuthConnection(
    url=URL, username="******", password=PASSWORD)

service = Exchange2010Service(connection)

my_calendar = service.calendar()

events = my_calendar.list_events(
    start=timezone("Europe/London").localize(datetime(2018, 01, 5)),
    end=timezone("Europe/London").localize(datetime(2018, 01, 10)),
    details=True)

for event in events:
    print "{start} {stop} - {subject}".format(start=event.start,
                                              stop=event.end,
                                              subject=event.subject)
示例#18
0
def establishexconn():
    global exservice
    exconnection = ExchangeNTLMAuthConnection(url=EX_URL,
                                              username=EX_USERNAME,
                                              password=EX_PASSWORD)
    exservice = Exchange2010Service(exconnection)