<commit_before>"""
The interface for accessing Trumba Calendars' Service 
"""

from restclients.models.trumba import TrumbaCalendar, Permission, is_bot, is_sea, is_tac
from restclients.exceptions import DataFailureException
from restclients.trumba.exceptions import CalendarOwnByDiffAccount, CalendarNotExist, NoDataReturned, UnknownError, UnexpectedError
from restclients.trumba import Trumba
import json
import logging
import re

class Calendar:
    """
    This class provides methods to obtain calendar info 
    and user calendar permissions in Trumba

    The underline http requests and responses will be logged.
    Be sure to set the logging configuration if you use the LiveDao!
    """

    get_calendarlist_url = "/service/calendars.asmx/GetCalendarList"
    get_permissions_url = "/service/calendars.asmx/GetPermissions"

    @staticmethod
    def get_campus_calendars(campus_code):
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to the given campus calendars.
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        if is_bot(campus_code):
            return Calendar.get_bot_calendars()
        elif is_sea(campus_code):
            return Calendar.get_sea_calendars()
        elif is_tac(campus_code):
            return Calendar.get_tac_calendars()
        else:
            None

    @staticmethod
    def get_bot_calendars():
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to Bothell calendars. 
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        return Calendar._process_get_cal_resp(
            Calendar.get_calendarlist_url,
            Trumba.post_bot_resource(Calendar.get_calendarlist_url,"{}"),
            TrumbaCalendar.BOT_CAMPUS_CODE)

    @staticmethod
    def get_sea_calendars():
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to Seattle calendars. 
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        return Calendar._process_get_cal_resp(
            Calendar.get_calendarlist_url,
            Trumba.post_sea_resource(Calendar.get_calendarlist_url,"{}"),
            TrumbaCalendar.SEA_CAMPUS_CODE)

    @staticmethod
    def get_tac_calendars():
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to Tacoma calendars. 
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        return Calendar._process_get_cal_resp(
            Calendar.get_calendarlist_url,
            Trumba.post_tac_resource(Calendar.get_calendarlist_url,"{}"),
            TrumbaCalendar.TAC_CAMPUS_CODE)

    @staticmethod
    def get_campus_permissions(calendar_id, campus_code):
        """
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        raise DataFailureException if the request failed.
        """
        if is_bot(campus_code):
            return Calendar.get_bot_permissions(calendar_id)
        elif is_sea(campus_code):
            return Calendar.get_sea_permissions(calendar_id)
        elif is_tac(campus_code):
            return Calendar.get_tac_permissions(calendar_id)
        else:
            None

    @staticmethod
    def _create_get_perm_body(calendar_id):
        return json.dumps({'CalendarID': calendar_id})

    @staticmethod
    def get_bot_permissions(calendar_id):
        """
        :param calendar_id: an integer representing calendar ID
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        Return a list of Permission objects representing
        the user permissions of a given Bothell calendar. 
        raise DataFailureException or a corresponding TrumbaException
        if the request failed or an error code has been returned.
        """
        return Calendar._process_get_perm_resp(
            Calendar.get_permissions_url,
            Trumba.post_bot_resource(Calendar.get_permissions_url,
                                     Calendar._create_get_perm_body(calendar_id)),
            TrumbaCalendar.BOT_CAMPUS_CODE,
            calendar_id)

    @staticmethod
    def get_sea_permissions(calendar_id):
        """
        Return a list of Permission objects representing
        the user permissions of a given Seattle calendar. 
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        raise DataFailureException or a corresponding TrumbaException
        if the request failed or an error code has been returned.
        """
        return Calendar._process_get_perm_resp(
            Calendar.get_permissions_url,
            Trumba.post_sea_resource(Calendar.get_permissions_url,
                                     Calendar._create_get_perm_body(calendar_id)),
            TrumbaCalendar.SEA_CAMPUS_CODE,
            calendar_id)

    @staticmethod
    def get_tac_permissions(calendar_id):
        """
        Return a list of Permission objects representing
        the user permissions of a given Tacoma calendar. 
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        raise DataFailureException or a corresponding TrumbaException
        if the request failed or an error code has been returned.
        """
        return Calendar._process_get_perm_resp(
            Calendar.get_permissions_url,
            Trumba.post_tac_resource(Calendar.get_permissions_url,
                                     Calendar._create_get_perm_body(calendar_id)),
            TrumbaCalendar.TAC_CAMPUS_CODE,
            calendar_id)

    re_cal_id = re.compile(r'[1-9]\d*')

    @staticmethod
    def _is_valid_calendarid(calendarid):
        return Calendar.re_cal_id.match(str(calendarid)) is not None

    @staticmethod
    def _load_calendar(campus, resp_fragment, calendar_dict):
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 None if error, {} if not exists
        """
        logger = logging.getLogger(__name__)
        for record in resp_fragment:
            if re.match('Internal Event Actions', record['Name']):
                continue
            trumba_cal = TrumbaCalendar()
            trumba_cal.calendarid = record['ID']
            trumba_cal.campus = campus
            trumba_cal.name = record['Name']
            if not Calendar._is_valid_calendarid(record['ID']):
                logger.warn(
                    "%s InvalidCalendarId, entry skipped!" % trumba_cal)
                continue
            calendar_dict[trumba_cal.calendarid] = trumba_cal
            if record['ChildCalendars'] is not None and len(record['ChildCalendars']) > 0:
                Calendar._load_calendar(campus, 
                                        record['ChildCalendars'], 
                                        calendar_dict)<commit_msg>Exclude Migrated events calendar.<commit_after>"""
The interface for accessing Trumba Calendars' Service 
"""

from restclients.models.trumba import TrumbaCalendar, Permission, is_bot, is_sea, is_tac
from restclients.exceptions import DataFailureException
from restclients.trumba.exceptions import CalendarOwnByDiffAccount, CalendarNotExist, NoDataReturned, UnknownError, UnexpectedError
from restclients.trumba import Trumba
import json
import logging
import re

class Calendar:
    """
    This class provides methods to obtain calendar info 
    and user calendar permissions in Trumba

    The underline http requests and responses will be logged.
    Be sure to set the logging configuration if you use the LiveDao!
    """

    get_calendarlist_url = "/service/calendars.asmx/GetCalendarList"
    get_permissions_url = "/service/calendars.asmx/GetPermissions"

    @staticmethod
    def get_campus_calendars(campus_code):
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to the given campus calendars.
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        if is_bot(campus_code):
            return Calendar.get_bot_calendars()
        elif is_sea(campus_code):
            return Calendar.get_sea_calendars()
        elif is_tac(campus_code):
            return Calendar.get_tac_calendars()
        else:
            None

    @staticmethod
    def get_bot_calendars():
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to Bothell calendars. 
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        return Calendar._process_get_cal_resp(
            Calendar.get_calendarlist_url,
            Trumba.post_bot_resource(Calendar.get_calendarlist_url,"{}"),
            TrumbaCalendar.BOT_CAMPUS_CODE)

    @staticmethod
    def get_sea_calendars():
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to Seattle calendars. 
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        return Calendar._process_get_cal_resp(
            Calendar.get_calendarlist_url,
            Trumba.post_sea_resource(Calendar.get_calendarlist_url,"{}"),
            TrumbaCalendar.SEA_CAMPUS_CODE)

    @staticmethod
    def get_tac_calendars():
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 corresponding to Tacoma calendars. 
                 None if error, {} if not exists
        raise DataFailureException if the request failed.
        """
        return Calendar._process_get_cal_resp(
            Calendar.get_calendarlist_url,
            Trumba.post_tac_resource(Calendar.get_calendarlist_url,"{}"),
            TrumbaCalendar.TAC_CAMPUS_CODE)

    @staticmethod
    def get_campus_permissions(calendar_id, campus_code):
        """
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        raise DataFailureException if the request failed.
        """
        if is_bot(campus_code):
            return Calendar.get_bot_permissions(calendar_id)
        elif is_sea(campus_code):
            return Calendar.get_sea_permissions(calendar_id)
        elif is_tac(campus_code):
            return Calendar.get_tac_permissions(calendar_id)
        else:
            None

    @staticmethod
    def _create_get_perm_body(calendar_id):
        return json.dumps({'CalendarID': calendar_id})

    @staticmethod
    def get_bot_permissions(calendar_id):
        """
        :param calendar_id: an integer representing calendar ID
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        Return a list of Permission objects representing
        the user permissions of a given Bothell calendar. 
        raise DataFailureException or a corresponding TrumbaException
        if the request failed or an error code has been returned.
        """
        return Calendar._process_get_perm_resp(
            Calendar.get_permissions_url,
            Trumba.post_bot_resource(Calendar.get_permissions_url,
                                     Calendar._create_get_perm_body(calendar_id)),
            TrumbaCalendar.BOT_CAMPUS_CODE,
            calendar_id)

    @staticmethod
    def get_sea_permissions(calendar_id):
        """
        Return a list of Permission objects representing
        the user permissions of a given Seattle calendar. 
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        raise DataFailureException or a corresponding TrumbaException
        if the request failed or an error code has been returned.
        """
        return Calendar._process_get_perm_resp(
            Calendar.get_permissions_url,
            Trumba.post_sea_resource(Calendar.get_permissions_url,
                                     Calendar._create_get_perm_body(calendar_id)),
            TrumbaCalendar.SEA_CAMPUS_CODE,
            calendar_id)

    @staticmethod
    def get_tac_permissions(calendar_id):
        """
        Return a list of Permission objects representing
        the user permissions of a given Tacoma calendar. 
        :return: a list of trumba.Permission objects
                 corresponding to the given campus calendar.
                 None if error, [] if not exists
        raise DataFailureException or a corresponding TrumbaException
        if the request failed or an error code has been returned.
        """
        return Calendar._process_get_perm_resp(
            Calendar.get_permissions_url,
            Trumba.post_tac_resource(Calendar.get_permissions_url,
                                     Calendar._create_get_perm_body(calendar_id)),
            TrumbaCalendar.TAC_CAMPUS_CODE,
            calendar_id)

    re_cal_id = re.compile(r'[1-9]\d*')

    @staticmethod
    def _is_valid_calendarid(calendarid):
        return Calendar.re_cal_id.match(str(calendarid)) is not None

    @staticmethod
    def _load_calendar(campus, resp_fragment, calendar_dict):
        """
        :return: a dictionary of {calenderid, TrumbaCalendar}
                 None if error, {} if not exists
        """
        logger = logging.getLogger(__name__)
        for record in resp_fragment:
            if re.match('Internal Event Actions', record['Name']) or re.match('Migrated events', record['Name']) :
                continue
            trumba_cal = TrumbaCalendar()
            trumba_cal.calendarid = record['ID']
            trumba_cal.campus = campus
            trumba_cal.name = record['Name']
            if not Calendar._is_valid_calendarid(record['ID']):
                logger.warn(
                    "%s InvalidCalendarId, entry skipped!" % trumba_cal)
                continue
            calendar_dict[trumba_cal.calendarid] = trumba_cal
            if record['ChildCalendars'] is not None and len(record['ChildCalendars']) > 0:
                Calendar._load_calendar(campus, 
                                        record['ChildCalendars'], 
                                        calendar_dict)
{'fraction_non_alphanumeric': 0.06321915975381322, 'fraction_numerical': 0.0004013914905004014, 'mean_word_length': 2.2294232015554116, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7224294', 'n_tokens_mistral': 3985, 'n_tokens_neox': 3850, 'n_words': 1036}