ぼざろクリーチャーシリーズ DB 兼 API(自分用)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1051 lines
35 KiB

  1. """
  2. 日次で実行し,ぼざクリ DB を最新に更新する.
  3. """
  4. from __future__ import annotations
  5. import json
  6. import os
  7. import random
  8. import string
  9. import time
  10. from dataclasses import dataclass
  11. from datetime import date, datetime, timedelta
  12. from typing import Any, Type, TypedDict, cast
  13. import mysql.connector
  14. import requests
  15. from mysql.connector.connection import MySQLConnectionAbstract
  16. class DbNull:
  17. def __new__ (
  18. cls,
  19. ):
  20. delattr (cls, '__init__')
  21. DbNullType = Type[DbNull]
  22. class VideoSearchParam (TypedDict):
  23. q: str
  24. targets: str
  25. _sort: str
  26. fields: str
  27. _limit: int
  28. jsonFilter: str
  29. class VideoResult (TypedDict):
  30. contentId: str
  31. title: str
  32. tags: str
  33. description: str | None
  34. viewCounter: int
  35. startTime: str
  36. class CommentResult (TypedDict):
  37. id: str
  38. no: int
  39. vposMs: int
  40. body: str
  41. commands: list[str]
  42. userId: str
  43. isPremium: bool
  44. score: int
  45. postedAt: str
  46. nicoruCount: int
  47. nicoruId: Any
  48. source: str
  49. isMyPost: bool
  50. class CommentRow (TypedDict):
  51. id: int
  52. video_id: int
  53. comment_no: int
  54. user_id: int
  55. content: str
  56. posted_at: datetime
  57. nico_count: int
  58. vpos_ms: int | None
  59. class TagRow (TypedDict):
  60. id: int
  61. name: str
  62. class UserRow (TypedDict):
  63. id: int
  64. code: str
  65. class VideoRow (TypedDict):
  66. id: int
  67. code: str
  68. title: str
  69. description: str
  70. uploaded_at: datetime
  71. deleted_at: datetime | None
  72. class VideoHistoryRow (TypedDict):
  73. id: int
  74. video_id: int
  75. fetched_at: date
  76. views_count: int
  77. class VideoTagRow (TypedDict):
  78. id: int
  79. video_id: int
  80. tag_id: int
  81. tagged_at: date
  82. untagged_at: date | None
  83. def main (
  84. ) -> None:
  85. conn = mysql.connector.connect (user = os.environ['MYSQL_USER'],
  86. password = os.environ['MYSQL_PASS'],
  87. database = 'nizika_nico')
  88. if not isinstance (conn, MySQLConnectionAbstract):
  89. raise TypeError
  90. now = datetime.now ()
  91. video_dao = VideoDao (conn)
  92. tag_dao = TagDao (conn)
  93. video_tag_dao = VideoTagDao (conn)
  94. video_history_dao = VideoHistoryDao (conn)
  95. comment_dao = CommentDao (conn)
  96. user_dao = UserDao (conn)
  97. api_data = search_nico_by_tags (['伊地知ニジカ', 'ぼざろクリーチャーシリーズ'])
  98. update_tables (video_dao, tag_dao, video_tag_dao, video_history_dao, comment_dao, user_dao,
  99. api_data, now)
  100. conn.commit ()
  101. conn.close ()
  102. def update_tables (
  103. video_dao: VideoDao,
  104. tag_dao: TagDao,
  105. video_tag_dao: VideoTagDao,
  106. video_history_dao: VideoHistoryDao,
  107. comment_dao: CommentDao,
  108. user_dao: UserDao,
  109. api_data: list[VideoResult],
  110. now: datetime,
  111. ) -> None:
  112. video_ids: list[int] = []
  113. for datum in api_data:
  114. tag_names: list[str] = datum['tags'].split ()
  115. video = VideoDto (code = datum['contentId'],
  116. title = datum['title'],
  117. description = datum['description'] or '',
  118. uploaded_at = datetime.fromisoformat (datum['startTime']))
  119. video_dao.upsert (video, False)
  120. if video.id_ is not None:
  121. video_ids.append (video.id_)
  122. video_history = VideoHistoryDto (video_id = video.id_,
  123. fetched_at = now,
  124. views_count = datum['viewCounter'])
  125. video_history_dao.insert (video_history)
  126. tag_ids: list[int] = []
  127. video_tags = video_tag_dao.fetch_alive_by_video_id (video.id_, False)
  128. for vt in video_tags:
  129. tag = tag_dao.find (vt.tag_id)
  130. if (tag is not None
  131. and (tag.name not in tag_names)
  132. and (tag.id_ is not None)):
  133. tag_ids.append (tag.id_)
  134. video_tag_dao.untag_all (video.id_, tag_ids, now)
  135. tags: list[TagDto] = []
  136. for tag_name in tag_names:
  137. tag = tag_dao.fetch_by_name (tag_name)
  138. if tag is None:
  139. tag = TagDto (name = tag_name)
  140. tag_dao.insert (tag)
  141. if video.id_ is not None and tag.id_ is not None:
  142. video_tag = video_tag_dao.fetch_alive_by_ids (video.id_, tag.id_, False)
  143. if video_tag is None:
  144. video_tag = VideoTagDto (video_id = video.id_,
  145. tag_id = tag.id_,
  146. tagged_at = now)
  147. video_tag_dao.insert (video_tag, False)
  148. for com in fetch_comments (video.code):
  149. user = user_dao.fetch_by_code (com['userId'])
  150. if user is None:
  151. user = UserDto (code = com['userId'])
  152. user_dao.insert (user)
  153. if video.id_ is not None and user.id_ is not None:
  154. comment = CommentDto (video_id = video.id_,
  155. comment_no = com['no'],
  156. user_id = user.id_,
  157. content = com['body'],
  158. posted_at = datetime.fromisoformat (com['postedAt']),
  159. nico_count = com['nicoruCount'],
  160. vpos_ms = com['vposMs'])
  161. comment_dao.upsert (comment, False)
  162. alive_video_codes = [d['contentId'] for d in api_data]
  163. lost_video_ids: list[int] = []
  164. videos = video_dao.fetch_alive ()
  165. for video in videos:
  166. if video.id_ is not None and video.code not in alive_video_codes:
  167. lost_video_ids.append (video.id_)
  168. video_dao.delete (lost_video_ids, now)
  169. def fetch_comments (
  170. video_code: str,
  171. ) -> list[CommentResult]:
  172. time.sleep (1.2)
  173. headers = { 'X-Frontend-Id': '6',
  174. 'X-Frontend-Version': '0' }
  175. action_track_id = (
  176. ''.join (random.choice (string.ascii_letters + string.digits)
  177. for _ in range (10))
  178. + '_'
  179. + str (random.randrange (10 ** 12, 10 ** 13)))
  180. url = (f"https://www.nicovideo.jp/api/watch/v3_guest/{ video_code }"
  181. + f"?actionTrackId={ action_track_id }")
  182. res = requests.post (url, headers = headers, timeout = 60).json ()
  183. try:
  184. nv_comment = res['data']['comment']['nvComment']
  185. except KeyError:
  186. return []
  187. if nv_comment is None:
  188. return []
  189. headers = { 'X-Frontend-Id': '6',
  190. 'X-Frontend-Version': '0',
  191. 'Content-Type': 'application/json' }
  192. params = { 'params': nv_comment['params'],
  193. 'additionals': { },
  194. 'threadKey': nv_comment['threadKey'] }
  195. url = nv_comment['server'] + '/v1/threads'
  196. res = (requests.post (url, json.dumps (params),
  197. headers = headers,
  198. timeout = 60)
  199. .json ())
  200. try:
  201. return res['data']['threads'][1]['comments']
  202. except (IndexError, KeyError):
  203. return []
  204. def search_nico_by_tag (
  205. tag: str,
  206. ) -> list[VideoResult]:
  207. return search_nico_by_tags ([tag])
  208. def search_nico_by_tags (
  209. tags: list[str],
  210. ) -> list[VideoResult]:
  211. today = datetime.now ()
  212. url = ('https://snapshot.search.nicovideo.jp'
  213. + '/api/v2/snapshot/video/contents/search')
  214. result_data: list[VideoResult] = []
  215. to = datetime (2022, 12, 3)
  216. while to <= today:
  217. time.sleep (1.2)
  218. until = to + timedelta (days = 14)
  219. query_filter = json.dumps ({ 'type': 'or',
  220. 'filters': [
  221. { 'type': 'range',
  222. 'field': 'startTime',
  223. 'from': '%04d-%02d-%02dT00:00:00+09:00' % (to.year, to.month, to.day),
  224. 'to': '%04d-%02d-%02dT23:59:59+09:00' % (until.year, until.month, until.day),
  225. 'include_lower': True }] })
  226. params: VideoSearchParam = { 'q': ' OR '.join (tags),
  227. 'targets': 'tagsExact',
  228. '_sort': '-viewCounter',
  229. 'fields': ('contentId,'
  230. 'title,'
  231. 'tags,'
  232. 'description,'
  233. 'viewCounter,'
  234. 'startTime'),
  235. '_limit': 100,
  236. 'jsonFilter': query_filter }
  237. res = requests.get (url, params = cast (dict[str, int | str], params), timeout = 60).json ()
  238. try:
  239. result_data += res['data']
  240. except KeyError:
  241. pass
  242. to = until + timedelta (days = 1)
  243. return result_data
  244. class VideoDao:
  245. def __init__ (
  246. self,
  247. conn: MySQLConnectionAbstract,
  248. ):
  249. self.conn = conn
  250. def find (
  251. self,
  252. video_id: int,
  253. with_relation_tables: bool,
  254. ) -> VideoDto | None:
  255. with self.conn.cursor (dictionary = True) as c:
  256. c.execute ("""
  257. SELECT
  258. id,
  259. code,
  260. title,
  261. description,
  262. uploaded_at,
  263. deleted_at
  264. FROM
  265. videos
  266. WHERE
  267. id = %s
  268. ORDER BY
  269. id""", (video_id,))
  270. row = cast (VideoRow | None, c.fetchone ())
  271. if row is None:
  272. return None
  273. return self._create_dto_from_row (row, with_relation_tables)
  274. def fetch_all (
  275. self,
  276. with_relation_tables: bool,
  277. ) -> list[VideoDto]:
  278. with self.conn.cursor (dictionary = True) as c:
  279. c.execute ("""
  280. SELECT
  281. id,
  282. code,
  283. title,
  284. description,
  285. uploaded_at,
  286. deleted_at
  287. FROM
  288. videos
  289. ORDER BY
  290. id""")
  291. videos: list[VideoDto] = []
  292. for row in cast (list[VideoRow], c.fetchall ()):
  293. videos.append (self._create_dto_from_row (row, with_relation_tables))
  294. return videos
  295. def fetch_alive (
  296. self,
  297. ) -> list[VideoDto]:
  298. with self.conn.cursor (dictionary = True) as c:
  299. c.execute ("""
  300. SELECT
  301. id,
  302. code,
  303. title,
  304. description,
  305. uploaded_at,
  306. deleted_at
  307. FROM
  308. videos
  309. WHERE
  310. deleted_at IS NULL""")
  311. videos: list[VideoDto] = []
  312. for row in cast (list[VideoRow], c.fetchall ()):
  313. videos.append (self._create_dto_from_row (row, False))
  314. return videos
  315. def upsert (
  316. self,
  317. video: VideoDto,
  318. with_relation_tables: bool,
  319. ) -> None:
  320. deleted_at: datetime | DbNullType | None = video.deleted_at
  321. if deleted_at is None:
  322. raise TypeError ('未実装')
  323. if deleted_at is DbNull:
  324. deleted_at = None
  325. deleted_at = cast (datetime | None, deleted_at)
  326. with self.conn.cursor (dictionary = True) as c:
  327. c.execute ("""
  328. INSERT INTO
  329. videos(
  330. code,
  331. title,
  332. description,
  333. uploaded_at,
  334. deleted_at)
  335. VALUES
  336. (
  337. %s,
  338. %s,
  339. %s,
  340. %s,
  341. %s)
  342. ON DUPLICATE KEY UPDATE
  343. id = LAST_INSERT_ID(id),
  344. code = VALUES(code),
  345. title = VALUES(title),
  346. description = VALUES(description),
  347. uploaded_at = VALUES(uploaded_at),
  348. deleted_at = VALUES(deleted_at)""", (video.code,
  349. video.title,
  350. video.description,
  351. video.uploaded_at,
  352. deleted_at))
  353. video.id_ = c.lastrowid
  354. if with_relation_tables:
  355. if video.video_tags is not None:
  356. VideoTagDao (self.conn).upsert_all (video.video_tags, False)
  357. if video.comments is not None:
  358. CommentDao (self.conn).upsert_all (video.comments, False)
  359. if video.video_histories is not None:
  360. VideoHistoryDao (self.conn).upsert_all (video.video_histories)
  361. def upsert_all (
  362. self,
  363. videos: list[VideoDto],
  364. with_relation_tables: bool,
  365. ) -> None:
  366. for video in videos:
  367. self.upsert (video, with_relation_tables)
  368. def delete (
  369. self,
  370. video_ids: list[int],
  371. at: datetime,
  372. ) -> None:
  373. if not video_ids:
  374. return
  375. with self.conn.cursor (dictionary = True) as c:
  376. c.execute ("""
  377. UPDATE
  378. videos
  379. SET
  380. deleted_at = %%s
  381. WHERE
  382. id IN (%s)""" % ', '.join (['%s'] * len (video_ids)), (at, *video_ids))
  383. def _create_dto_from_row (
  384. self,
  385. row: VideoRow,
  386. with_relation_tables: bool,
  387. ) -> VideoDto:
  388. video = VideoDto (id_ = row['id'],
  389. code = row['code'],
  390. title = row['title'],
  391. description = row['description'],
  392. uploaded_at = row['uploaded_at'],
  393. deleted_at = row['deleted_at'] or DbNull)
  394. if with_relation_tables and video.id_ is not None:
  395. video.video_tags = VideoTagDao (self.conn).fetch_by_video_id (video.id_, False)
  396. for i in range (len (video.video_tags)):
  397. video.video_tags[i].video = video
  398. video.comments = CommentDao (self.conn).fetch_by_video_id (video.id_, False)
  399. for i in range (len (video.comments)):
  400. video.comments[i].video = video
  401. video.video_histories = VideoHistoryDao (self.conn).fetch_by_video_id (video.id_, False)
  402. for i in range (len (video.video_histories)):
  403. video.video_histories[i].video = video
  404. return video
  405. @dataclass (slots = True)
  406. class VideoDto:
  407. code: str
  408. title: str
  409. description: str
  410. uploaded_at: datetime
  411. id_: int | None = None
  412. deleted_at: datetime | DbNullType = DbNull
  413. video_tags: list[VideoTagDto] | None = None
  414. comments: list[CommentDto] | None = None
  415. video_histories: list[VideoHistoryDto] | None = None
  416. class VideoTagDao:
  417. def __init__ (
  418. self,
  419. conn: MySQLConnectionAbstract,
  420. ):
  421. self.conn = conn
  422. def fetch_by_video_id (
  423. self,
  424. video_id: int,
  425. with_relation_tables: bool,
  426. ) -> list[VideoTagDto]:
  427. with self.conn.cursor (dictionary = True) as c:
  428. c.execute ("""
  429. SELECT
  430. id,
  431. video_id,
  432. tag_id,
  433. tagged_at,
  434. untagged_at
  435. FROM
  436. video_tags
  437. WHERE
  438. video_id = %s
  439. ORDER BY
  440. id""", (video_id,))
  441. video_tags: list[VideoTagDto] = []
  442. for row in cast (list[VideoTagRow], c.fetchall ()):
  443. video_tags.append (self._create_dto_from_row (row, with_relation_tables))
  444. return video_tags
  445. def fetch_alive_by_video_id (
  446. self,
  447. video_id: int,
  448. with_relation_tables: bool,
  449. ) -> list[VideoTagDto]:
  450. with self.conn.cursor (dictionary = True) as c:
  451. c.execute ("""
  452. SELECT
  453. id,
  454. video_id,
  455. tag_id,
  456. tagged_at,
  457. untagged_at
  458. FROM
  459. video_tags
  460. WHERE
  461. video_id = %s
  462. AND (untagged_at IS NULL)
  463. ORDER BY
  464. id""", (video_id,))
  465. video_tags: list[VideoTagDto] = []
  466. for row in cast (list[VideoTagRow], c.fetchall ()):
  467. video_tags.append (self._create_dto_from_row (row, with_relation_tables))
  468. return video_tags
  469. def fetch_alive_by_ids (
  470. self,
  471. video_id: int,
  472. tag_id: int,
  473. with_relation_tables: bool,
  474. ) -> VideoTagDto | None:
  475. with self.conn.cursor (dictionary = True) as c:
  476. c.execute ("""
  477. SELECT
  478. id,
  479. video_id,
  480. tag_id,
  481. tagged_at,
  482. untagged_at
  483. FROM
  484. video_tags
  485. WHERE
  486. video_id = %s
  487. AND tag_id = %s""", (video_id, tag_id))
  488. row = cast (VideoTagRow, c.fetchone ())
  489. if row is None:
  490. return None
  491. return self._create_dto_from_row (row, with_relation_tables)
  492. def insert (
  493. self,
  494. video_tag: VideoTagDto,
  495. with_relation_tables: bool,
  496. ) -> None:
  497. untagged_at: date | DbNullType | None = video_tag.untagged_at
  498. if untagged_at is None:
  499. raise TypeError ('未実装')
  500. if untagged_at is DbNull:
  501. untagged_at = None
  502. untagged_at = cast (date | None, untagged_at)
  503. with self.conn.cursor (dictionary = True) as c:
  504. c.execute ("""
  505. INSERT INTO
  506. video_tags(
  507. video_id,
  508. tag_id,
  509. tagged_at,
  510. untagged_at)
  511. VALUES
  512. (
  513. %s,
  514. %s,
  515. %s,
  516. %s)""", (video_tag.video_id, video_tag.tag_id,
  517. video_tag.tagged_at, untagged_at))
  518. video_tag.id_ = c.lastrowid
  519. if with_relation_tables:
  520. if video_tag.video is not None:
  521. VideoDao (self.conn).upsert (video_tag.video, True)
  522. if video_tag.tag is not None:
  523. TagDao (self.conn).upsert (video_tag.tag)
  524. def upsert (
  525. self,
  526. video_tag: VideoTagDto,
  527. with_relation_tables: bool,
  528. ) -> None:
  529. untagged_at: date | DbNullType | None = video_tag.untagged_at
  530. if untagged_at is None:
  531. raise TypeError ('未実装')
  532. if untagged_at is DbNull:
  533. untagged_at = None
  534. untagged_at = cast (date | None, untagged_at)
  535. with self.conn.cursor (dictionary = True) as c:
  536. c.execute ("""
  537. INSERT INTO
  538. video_tags(
  539. video_id,
  540. tag_id,
  541. tagged_at,
  542. untagged_at)
  543. VALUES
  544. (
  545. %s,
  546. %s,
  547. %s,
  548. %s)
  549. ON DUPLICATE KEY UPDATE
  550. id = LAST_INSERT_ID(id),
  551. video_id = VALUES(video_id),
  552. tag_id = VALUES(tag_id),
  553. tagged_at = VALUES(tagged_at),
  554. untagged_at = VALUES(untagged_at)""", (video_tag.video_id,
  555. video_tag.tag_id,
  556. video_tag.tagged_at,
  557. untagged_at))
  558. video_tag.id_ = c.lastrowid
  559. if with_relation_tables:
  560. if video_tag.video is not None:
  561. VideoDao (self.conn).upsert (video_tag.video, True)
  562. if video_tag.tag is not None:
  563. TagDao (self.conn).upsert (video_tag.tag)
  564. def upsert_all (
  565. self,
  566. video_tags: list[VideoTagDto],
  567. with_relation_tables: bool,
  568. ) -> None:
  569. for video_tag in video_tags:
  570. self.upsert (video_tag, with_relation_tables)
  571. def untag_all (
  572. self,
  573. video_id: int,
  574. tag_ids: list[int],
  575. now: datetime,
  576. ) -> None:
  577. if not tag_ids:
  578. return
  579. with self.conn.cursor (dictionary = True) as c:
  580. c.execute ("""
  581. UPDATE
  582. video_tags
  583. SET
  584. untagged_at = %%s
  585. WHERE
  586. video_id = %%s
  587. AND tag_id IN (%s)""" % ', '.join (['%s'] * len (tag_ids)), (now, video_id, *tag_ids))
  588. def _create_dto_from_row (
  589. self,
  590. row: VideoTagRow,
  591. with_relation_tables: bool,
  592. ) -> VideoTagDto:
  593. video_tag = VideoTagDto (id_ = row['id'],
  594. video_id = row['video_id'],
  595. tag_id = row['tag_id'],
  596. tagged_at = row['tagged_at'],
  597. untagged_at = row['untagged_at'] or DbNull)
  598. if with_relation_tables:
  599. video_tag.video = VideoDao (self.conn).find (video_tag.video_id, True)
  600. video_tag.tag = TagDao (self.conn).find (video_tag.tag_id)
  601. return video_tag
  602. @dataclass (slots = True)
  603. class VideoTagDto:
  604. video_id: int
  605. tag_id: int
  606. tagged_at: date
  607. id_: int | None = None
  608. untagged_at: date | DbNullType = DbNull
  609. video: VideoDto | None = None
  610. tag: TagDto | None = None
  611. class TagDao:
  612. def __init__ (
  613. self,
  614. conn: MySQLConnectionAbstract,
  615. ):
  616. self.conn = conn
  617. def find (
  618. self,
  619. tag_id: int,
  620. ) -> TagDto | None:
  621. with self.conn.cursor (dictionary = True) as c:
  622. c.execute ("""
  623. SELECT
  624. id,
  625. name
  626. FROM
  627. tags
  628. WHERE
  629. id = %s""", (tag_id,))
  630. row = cast (TagRow | None, c.fetchone ())
  631. if row is None:
  632. return None
  633. return self._create_dto_from_row (row)
  634. def fetch_by_name (
  635. self,
  636. tag_name: str,
  637. ) -> TagDto | None:
  638. with self.conn.cursor (dictionary = True) as c:
  639. c.execute ("""
  640. SELECT
  641. id,
  642. name
  643. FROM
  644. tags
  645. WHERE
  646. name = %s""", (tag_name,))
  647. row = cast (TagRow | None, c.fetchone ())
  648. if row is None:
  649. return None
  650. return self._create_dto_from_row (row)
  651. def insert (
  652. self,
  653. tag: TagDto,
  654. ) -> None:
  655. with self.conn.cursor (dictionary = True) as c:
  656. c.execute ("""
  657. INSERT INTO
  658. tags(name)
  659. VALUES
  660. (%s)""", (tag.name,))
  661. tag.id_ = c.lastrowid
  662. def upsert (
  663. self,
  664. tag: TagDto,
  665. ) -> None:
  666. with self.conn.cursor (dictionary = True) as c:
  667. c.execute ("""
  668. INSERT INTO
  669. tags(name)
  670. VALUES
  671. (%s)
  672. ON DUPLICATE KEY UPDATE
  673. id = LAST_INSERT_ID(id),
  674. name = VALUES(name)""", (tag.name,))
  675. tag.id_ = c.lastrowid
  676. def _create_dto_from_row (
  677. self,
  678. row: TagRow,
  679. ) -> TagDto:
  680. return TagDto (id_ = row['id'],
  681. name = row['name'])
  682. @dataclass (slots = True)
  683. class TagDto:
  684. name: str
  685. id_: int | None = None
  686. class VideoHistoryDao:
  687. def __init__ (
  688. self,
  689. conn: MySQLConnectionAbstract,
  690. ):
  691. self.conn = conn
  692. def fetch_by_video_id (
  693. self,
  694. video_id: int,
  695. with_relation_tables: bool,
  696. ) -> list[VideoHistoryDto]:
  697. with self.conn.cursor (dictionary = True) as c:
  698. c.execute ("""
  699. SELECT
  700. id,
  701. video_id,
  702. fetched_at,
  703. views_count
  704. FROM
  705. video_histories
  706. WHERE
  707. video_id = %s""", (video_id,))
  708. video_histories: list[VideoHistoryDto] = []
  709. for row in cast (list[VideoHistoryRow], c.fetchall ()):
  710. video_histories.append (self._create_dto_from_row (row, with_relation_tables))
  711. return video_histories
  712. def insert (
  713. self,
  714. video_history: VideoHistoryDto,
  715. ) -> None:
  716. with self.conn.cursor (dictionary = True) as c:
  717. c.execute ("""
  718. INSERT INTO
  719. video_histories(
  720. video_id,
  721. fetched_at,
  722. views_count)
  723. VALUES
  724. (
  725. %s,
  726. %s,
  727. %s)""", (video_history.video_id,
  728. video_history.fetched_at,
  729. video_history.views_count))
  730. def upsert (
  731. self,
  732. video_history: VideoHistoryDto,
  733. ) -> None:
  734. with self.conn.cursor (dictionary = True) as c:
  735. c.execute ("""
  736. INSERT INTO
  737. video_histories(
  738. video_id,
  739. fetched_at,
  740. views_count)
  741. VALUES
  742. (
  743. %s,
  744. %s,
  745. %s)
  746. ON DUPLICATE KEY UPDATE
  747. id = LAST_INSERT_ID(id),
  748. video_id = VALUES(video_id),
  749. fetched_at = VALUES(fetched_at),
  750. views_count = VALUES(views_count)""", (video_history.video_id,
  751. video_history.fetched_at,
  752. video_history.views_count))
  753. def upsert_all (
  754. self,
  755. video_histories: list[VideoHistoryDto],
  756. ) -> None:
  757. for video_history in video_histories:
  758. self.upsert (video_history)
  759. def _create_dto_from_row (
  760. self,
  761. row: VideoHistoryRow,
  762. with_relation_tables: bool,
  763. ) -> VideoHistoryDto:
  764. video_history = VideoHistoryDto (id_ = row['id'],
  765. video_id = row['video_id'],
  766. fetched_at = row['fetched_at'],
  767. views_count = row['views_count'])
  768. if with_relation_tables:
  769. video_history.video = VideoDao (self.conn).find (video_history.video_id, True)
  770. return video_history
  771. @dataclass (slots = True)
  772. class VideoHistoryDto:
  773. video_id: int
  774. fetched_at: date
  775. views_count: int
  776. id_: int | None = None
  777. video: VideoDto | None = None
  778. class CommentDao:
  779. def __init__ (
  780. self,
  781. conn: MySQLConnectionAbstract,
  782. ):
  783. self.conn = conn
  784. def fetch_by_video_id (
  785. self,
  786. video_id: int,
  787. with_relation_tables: bool,
  788. ) -> list[CommentDto]:
  789. with self.conn.cursor (dictionary = True) as c:
  790. c.execute ("""
  791. SELECT
  792. id,
  793. video_id,
  794. comment_no,
  795. user_id,
  796. content,
  797. posted_at,
  798. nico_count,
  799. vpos_ms
  800. FROM
  801. comments
  802. WHERE
  803. video_id = %s""", (video_id,))
  804. comments: list[CommentDto] = []
  805. for row in cast (list[CommentRow], c.fetchall ()):
  806. comments.append (self._create_dto_from_row (row, with_relation_tables))
  807. return comments
  808. def upsert (
  809. self,
  810. comment: CommentDto,
  811. with_relation_tables: bool,
  812. ) -> None:
  813. vpos_ms: int | DbNullType | None = comment.vpos_ms
  814. if vpos_ms is None:
  815. raise TypeError ('未実装')
  816. if vpos_ms is DbNull:
  817. vpos_ms = None
  818. vpos_ms = cast (int | None, vpos_ms)
  819. with self.conn.cursor (dictionary = True) as c:
  820. c.execute ("""
  821. INSERT INTO
  822. comments(
  823. video_id,
  824. comment_no,
  825. user_id,
  826. content,
  827. posted_at,
  828. nico_count,
  829. vpos_ms)
  830. VALUES
  831. (
  832. %s,
  833. %s,
  834. %s,
  835. %s,
  836. %s,
  837. %s,
  838. %s)
  839. ON DUPLICATE KEY UPDATE
  840. id = LAST_INSERT_ID(id),
  841. video_id = VALUES(video_id),
  842. comment_no = VALUES(comment_no),
  843. user_id = VALUES(user_id),
  844. content = VALUES(content),
  845. posted_at = VALUES(posted_at),
  846. nico_count = VALUES(nico_count),
  847. vpos_ms = VALUES(vpos_ms)""", (comment.video_id,
  848. comment.comment_no,
  849. comment.user_id,
  850. comment.content,
  851. comment.posted_at,
  852. comment.nico_count,
  853. vpos_ms))
  854. def upsert_all (
  855. self,
  856. comments: list[CommentDto],
  857. with_relation_tables: bool,
  858. ) -> None:
  859. for comment in comments:
  860. self.upsert (comment, with_relation_tables)
  861. def _create_dto_from_row (
  862. self,
  863. row: CommentRow,
  864. with_relation_tables: bool,
  865. ) -> CommentDto:
  866. comment = CommentDto (id_ = row['id'],
  867. video_id = row['video_id'],
  868. comment_no = row['comment_no'],
  869. user_id = row['user_id'],
  870. content = row['content'],
  871. posted_at = row['posted_at'],
  872. nico_count = row['nico_count'],
  873. vpos_ms = row['vpos_ms'] or DbNull)
  874. if with_relation_tables:
  875. comment.video = VideoDao (self.conn).find (comment.video_id, True)
  876. return comment
  877. @dataclass (slots = True)
  878. class CommentDto:
  879. video_id: int
  880. comment_no: int
  881. user_id: int
  882. content: str
  883. posted_at: datetime
  884. id_: int | None = None
  885. nico_count: int = 0
  886. vpos_ms: int | DbNullType = DbNull
  887. video: VideoDto | None = None
  888. user: UserDto | None = None
  889. class UserDao:
  890. def __init__ (
  891. self,
  892. conn: MySQLConnectionAbstract,
  893. ):
  894. self.conn = conn
  895. def fetch_by_code (
  896. self,
  897. user_code: str
  898. ) -> UserDto | None:
  899. with self.conn.cursor (dictionary = True) as c:
  900. c.execute ("""
  901. SELECT
  902. id,
  903. code
  904. FROM
  905. users
  906. WHERE
  907. code = %s""", (user_code,))
  908. row = cast (UserRow | None, c.fetchone ())
  909. if row is None:
  910. return None
  911. return self._create_dto_from_row (row)
  912. def insert (
  913. self,
  914. user: UserDto,
  915. ) -> None:
  916. with self.conn.cursor (dictionary = True) as c:
  917. c.execute ("""
  918. INSERT INTO
  919. users(code)
  920. VALUES
  921. (%s)""", (user.code,))
  922. user.id_ = c.lastrowid
  923. def _create_dto_from_row (
  924. self,
  925. row: UserRow,
  926. ) -> UserDto:
  927. return UserDto (id_ = row['id'],
  928. code = row['code'])
  929. @dataclass (slots = True)
  930. class UserDto:
  931. code: str
  932. id_: int | None = None
  933. if __name__ == '__main__':
  934. main ()