|
| 1 | +import json |
| 2 | +import os |
| 3 | +from math import ceil |
| 4 | +from typing import List, Dict, Any, Union, Tuple |
| 5 | +import json |
| 6 | +from urllib.request import Request |
| 7 | +from urllib import request, parse, error |
| 8 | +from http.client import HTTPResponse |
| 9 | + |
| 10 | + |
| 11 | +class Response(): |
| 12 | + """Http Response Object""" |
| 13 | + |
| 14 | + def __init__(self, res: HTTPResponse): |
| 15 | + self.body = self._json(res) |
| 16 | + self.status_code = self._status_code(res) |
| 17 | + self.headers = self._headers(res) |
| 18 | + |
| 19 | + def _json(self, res: HTTPResponse): |
| 20 | + return json.loads(res.read()) |
| 21 | + |
| 22 | + def _status_code(self, res: HTTPResponse) -> int: |
| 23 | + return res.status |
| 24 | + |
| 25 | + def _headers(self, res: HTTPResponse) -> Dict[str, str]: |
| 26 | + return dict(res.getheaders()) |
| 27 | + |
| 28 | + |
| 29 | +def req_get(url: str, headers=None, params=None) -> Response: |
| 30 | + """get request. simplified request function of Requests |
| 31 | + :return: Response object |
| 32 | + """ |
| 33 | + if params: |
| 34 | + url = '{}?{}'.format(url, parse.urlencode(params)) |
| 35 | + |
| 36 | + req = Request(url, headers=headers, method='GET') |
| 37 | + |
| 38 | + with request.urlopen(req) as res: |
| 39 | + response = Response(res) |
| 40 | + return response |
| 41 | + |
| 42 | + |
| 43 | +def req_post(url: str, data: Dict[str, Any], headers=None, params=None) -> Response: |
| 44 | + """post request. simplified request function of Requests |
| 45 | + :return: Response object |
| 46 | + """ |
| 47 | + if headers.get('Content-Type') == 'application/x-www-form-urlencoded': |
| 48 | + encoded_data = parse.urlencode(data).encode() |
| 49 | + |
| 50 | + else: |
| 51 | + encoded_data = json.dumps(data).encode() |
| 52 | + |
| 53 | + req = Request(url, data=encoded_data, headers=headers, method='POST') |
| 54 | + |
| 55 | + with request.urlopen(req) as res: |
| 56 | + response = Response(res) |
| 57 | + return response |
| 58 | + |
| 59 | + |
| 60 | +def serialize_record(record: Dict[str, Any]) -> Dict[str, Any]: |
| 61 | + """serialize data of Dynamo DB Stream |
| 62 | + :return: |
| 63 | + """ |
| 64 | + if record.get('eventName') != 'MODIFY': |
| 65 | + return {} |
| 66 | + |
| 67 | + past = record.get('dynamodb', {}).get('OldImage') |
| 68 | + past_iine = int(past.get('iine', {}).get('N', 0)) |
| 69 | + ids = past.get('ids', {}).get('S', '') |
| 70 | + |
| 71 | + new = record.get('dynamodb', {}).get('NewImage') |
| 72 | + title = new.get('title', {}).get('S', '') |
| 73 | + return { |
| 74 | + 'ids': ids, |
| 75 | + 'title': title, |
| 76 | + 'past_iine': past_iine |
| 77 | + } |
| 78 | + |
| 79 | + |
| 80 | +def serialize_response_name(response: Response, num: int, title: str) -> Dict[str, Any]: |
| 81 | + """serialize iine data of Qiita API v2 |
| 82 | + :param response: |
| 83 | + :return: |
| 84 | + """ |
| 85 | + size = len(response.body) - num |
| 86 | + if size <= 0: |
| 87 | + users: List[str] = [] |
| 88 | + |
| 89 | + new_iine = response.body[:size] |
| 90 | + users = [ |
| 91 | + resp.get('user', {}).get('id') for resp in new_iine |
| 92 | + ] |
| 93 | + return { |
| 94 | + 'title': title, |
| 95 | + 'users': users |
| 96 | + } |
| 97 | + |
| 98 | + |
| 99 | +def get_new_iine(item: Dict[str, Any], token: str) -> Dict[str, Any]: |
| 100 | + """HTTP request to Qiita API v2 |
| 101 | + :params: |
| 102 | + :return: |
| 103 | + """ |
| 104 | + headers = {'Authorization': 'Bearer {}'.format(token)} |
| 105 | + ids = item.get('ids', '') |
| 106 | + past_iine = item.get('past_iine', 0) |
| 107 | + url = f'https://qiita.com/api/v2/items/{ids}/likes' |
| 108 | + |
| 109 | + response = req_get(url, headers=headers) |
| 110 | + title: str = item.get('title', '') |
| 111 | + resp = serialize_response_name(response, past_iine, title) |
| 112 | + return resp |
| 113 | + |
| 114 | + |
| 115 | +def deserialize_response_name(response: Dict[str, Any], max_length=20) -> str: |
| 116 | + """deserialize text for LINE Notify |
| 117 | + :param max_length: max sentence length |
| 118 | + :return: |
| 119 | + """ |
| 120 | + names = ", ".join(response.get('users', [])) |
| 121 | + title = response.get('title', '') |
| 122 | + title = f"{title}" if len(title) <= max_length else f"{title[:max_length]}..." |
| 123 | + return f"\n{names}が「{title}」にいいねしました。" |
| 124 | + |
| 125 | + |
| 126 | +def send_notification(message: str, token: str): |
| 127 | + """send notification by LINE notify""" |
| 128 | + url = 'https://notify-api.line.me/api/notify' |
| 129 | + |
| 130 | + headers = { |
| 131 | + 'Authorization': 'Bearer {}'.format(token), |
| 132 | + 'Content-Type': 'application/x-www-form-urlencoded' |
| 133 | + } |
| 134 | + msg = { |
| 135 | + 'message': message |
| 136 | + } |
| 137 | + response = req_post(url, data=msg, headers=headers) |
| 138 | + return response.body |
| 139 | + |
| 140 | + |
| 141 | +def lambda_handler(event, context): |
| 142 | + """main handler for Lambda""" |
| 143 | + qiita_token = os.environ["QIITA_TOKEN"] |
| 144 | + line_token = os.environ["LINE_TOKEN"] |
| 145 | + |
| 146 | + records = event.get('Records', []) |
| 147 | + for record in records: |
| 148 | + serialized_data = serialize_record(record) |
| 149 | + if not serialized_data: |
| 150 | + continue |
| 151 | + new_iines = get_new_iine(serialized_data, qiita_token) |
| 152 | + if len(new_iines.get('users')) == 0: |
| 153 | + continue |
| 154 | + send_notification(deserialize_response_name(new_iines), line_token) |
| 155 | + |
| 156 | + return { |
| 157 | + 'statusCode': 200, |
| 158 | + } |
0 commit comments