Ejemplo n.º 1
0
    def __init__(self, app_name, user_name, credential_root, logger=None):
        self.logger = LogUtil.get_logger(
            app_name=app_name) if logger is None else logger

        self.service = CredentialManager(logger=self.logger).service(
            service_name=ServiceMap.SHEETS,
            app_name=app_name,
            user_name=user_name,
            credential_root=credential_root)
Ejemplo n.º 2
0
class YangsGoogleDrive:
    def __init__(self, app_name, user_name, credential_root, logger=None):
        self.logger = LogUtil.get_logger(
            app_name=app_name) if logger is None else logger

        self.service = CredentialManager(logger=self.logger).service(
            service_name=ServiceMap.SHEETS,
            app_name=app_name,
            user_name=user_name,
            credential_root=credential_root)

    # public
    def download(self, file_id, file_type, file_path):
        FileUtil.make_folder(file_path)

        request = self.service.files().export_media(fileId=file_id,
                                                    mimeType=file_type)

        fh = io.FileIO(file_path, 'wb')
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            self.logger.info("Download %d%%." % int(status.progress() * 100))
Ejemplo n.º 3
0
class YangsGoogleCalendar:
    def __init__(self, app_name, user_name, credential_root, logger=None):
        self.logger = LogUtil.get_logger(
            app_name=app_name) if logger is None else logger

        self.service = CredentialManager(logger=self.logger).service(
            service_name=ServiceMap.CALENDAR,
            app_name=app_name,
            user_name=user_name,
            credential_root=credential_root)

        self.holiday_list = None

    # public
    def get_holiday_list(self):

        basic = DateTimeUtil.get_string(output_form='%Y')

        last_year = DateTimeUtil.get_object(src_object=basic,
                                            src_object_form='%Y',
                                            gap=-1,
                                            datetime_type=DateTimeUtil.YEARS)

        next_year = DateTimeUtil.get_object(src_object=DateTimeUtil.get_object(
            src_object=basic,
            src_object_form='%Y',
            gap=2,
            datetime_type=DateTimeUtil.YEARS),
                                            gap=-1)

        event_results = self.service.events().list(
            calendarId='ko.south_korea#[email protected]',
            timeMin=last_year.isoformat() + 'Z',
            timeMax=next_year.isoformat() + 'Z',
            singleEvents=True,
            orderBy='startTime').execute()

        events = event_results.get('items', [])

        return [{
            'date': event['start']['date'],
            'name': event['summary']
        } for event in events]

    def is_holiday(self, datetime=None, datetime_form='%Y%m%d'):

        if self.holiday_list is None:
            self.holiday_list = self.get_holiday_list()

        event_list = self.holiday_list

        target_date = DateTimeUtil.get_string(src_object=datetime,
                                              src_object_form=datetime_form,
                                              output_form='%Y-%m-%d')

        target_event = None
        for event in event_list:
            if event['date'] == target_date:
                target_event = event
                break

        if target_event is None:
            return False

        name = target_event['name']
        if name in HOLIDAY_LIST:
            return True

        is_holiday = False
        for contain in CONTAIN_HOLIDAY_NAME:

            if type(contain) == list:

                flag = True
                for contain_item in contain:
                    if contain_item not in name:
                        flag = False

                if flag is True:
                    is_holiday = True
                    break

            else:
                if contain in name:
                    is_holiday = True
                    break

        return is_holiday
Ejemplo n.º 4
0
class YangsGoogleSheets:
    def __init__(self, app_name, user_name, credential_root, logger=None):
        self.logger = LogUtil.get_logger(
            app_name=app_name) if logger is None else logger

        self.service = CredentialManager(logger=self.logger).service(
            service_name=ServiceMap.SHEETS,
            app_name=app_name,
            user_name=user_name,
            credential_root=credential_root)

    # public
    def read(self, option):

        if option is None:
            self.logger.info('option is None')
            return

        sheet_id = option['id']
        self.logger.debug("Sheet ID >> %s" % sheet_id)

        if type(option['range']) is str:

            sheet_range = '%s!%s' % (option['sheet'], option['range'])
            self.logger.debug("Sheet range >> %s" % sheet_range)

            result = self.service.spreadsheets().values().get(
                spreadsheetId=sheet_id, range=sheet_range).execute()
            values = result.get('values', [])

        elif type(option['range']) is list:

            sheet_ranges = [('%s!%s' % (option['sheet'], range_item))
                            for range_item in option['range']]
            self.logger.debug("Sheet range >> %s" %
                              Printer.list(sheet_ranges, is_show=False))

            result = self.service.spreadsheets().values().batchGet(
                spreadsheetId=sheet_id, ranges=sheet_ranges).execute()
            values = result.get('values', [])
        else:
            values = []

        return values

    def write(self, option, data):
        if option is None:
            self.logger.info('option is None')
            return

        if len(data) == 0 or data is None:
            self.logger.info('data is None')
            return

        sheet_id = option['id']
        self.logger.debug("Sheet ID >> %s" % sheet_id)

        if type(data[0]) == dict:  # multiple range

            for one_data in data:
                one_data['range'] = '%s!%s' % (option['sheet'],
                                               one_data['range'])
                self.logger.debug("Sheet range >> %s" % one_data['range'])

            result = self.service.spreadsheets().values().batchUpdate(
                spreadsheetId=sheet_id,
                body={
                    'valueInputOption': "USER_ENTERED",
                    'data': data
                }).execute()
            self.logger.info('Result : %s' % str(result))

        elif type(data[0]) == list:  # one range

            sheet_range = '%s!%s' % (option['sheet'], option['range'])
            self.logger.debug("Sheet range >> %s" % sheet_range)

            result = self.service.spreadsheets().values().update(
                spreadsheetId=sheet_id,
                range=sheet_range,
                valueInputOption="USER_ENTERED",
                body={
                    "majorDimension": "ROWS",
                    "values": data
                }).execute()
            self.logger.info('Result : %s' % str(result))

        else:
            pass

    def append(self, option, data, insert_option=None):

        if option is None:
            self.logger.info('option is None')
            return

        if len(data) == 0 or data is None:
            self.logger.info('data is None')
            return

        sheet_id = option['id']
        self.logger.debug("Sheet ID >> %s" % sheet_id)

        sheet_range = '%s!%s' % (option['sheet'], option['range'])
        self.logger.debug("Sheet range >> %s" % sheet_range)

        if insert_option is None:
            starter = self.service.spreadsheets().values().append(
                spreadsheetId=sheet_id,
                range=sheet_range,
                valueInputOption="USER_ENTERED",
                body={
                    "majorDimension": "ROWS",
                    "values": data
                })

        else:
            starter = self.service.spreadsheets().values().append(
                spreadsheetId=sheet_id,
                range=sheet_range,
                valueInputOption="USER_ENTERED",
                insertDataOption=insert_option,
                body={
                    "majorDimension": "ROWS",
                    "values": data
                })

        input_result = starter.execute()
        self.logger.info("Result : %s" % str(input_result))
Ejemplo n.º 5
0
class YangsGoogleMail:
    def __init__(self, app_name, user_name, credential_root, logger=None):
        self.logger = LogUtil.get_logger(
            app_name=app_name) if logger is None else logger

        self.service = CredentialManager(logger=self.logger).service(
            service_name=ServiceMap.GMAIL,
            app_name=app_name,
            user_name=user_name,
            credential_root=credential_root)

    # public
    def send(self, option, subject, content, _subtype='plain'):
        message = MIMEText(content, _subtype)

        message['subject'] = subject
        message['to'] = option['to']

        try:
            message['from'] = option['from']
        except KeyError:
            message['from'] = '*****@*****.**'

        try:
            message['cc'] = option['cc']
        except KeyError:
            pass

        message_body = {
            'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')
        }

        return self.service.users().messages().send(
            userId="me", body=message_body).execute()

    def send_with_file(self, option, subject, content, file, _subtype='plain'):
        message = MIMEMultipart()
        message['subject'] = subject
        message['to'] = option['to']

        try:
            message['from'] = option['from']
        except KeyError:
            message['from'] = '*****@*****.**'

        try:
            message['cc'] = option['cc']
        except KeyError:
            pass

        msg = MIMEText(content, _subtype)
        message.attach(msg)

        content_type, encoding = mimetypes.guess_type(file)

        if content_type is None or encoding is not None:
            content_type = 'application/octet-stream'

        main_type, sub_type = content_type.split('/', 1)
        if main_type == 'text':
            fp = open(file, 'rb')
            msg = MIMEText(fp.read(), _subtype=sub_type)
            fp.close()
        elif main_type == 'image':
            fp = open(file, 'rb')
            msg = MIMEImage(fp.read(), _subtype=sub_type)
            fp.close()
        elif main_type == 'audio':
            fp = open(file, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=sub_type)
            fp.close()
        else:
            fp = open(file, 'rb')
            msg = MIMEBase(main_type, sub_type)
            msg.set_payload(fp.read())
            fp.close()

        filename = os.path.basename(file)
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        message.attach(msg)

        message_body = {
            'raw': base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')
        }

        return self.service.users().messages().send(
            userId="me", body=message_body).execute()