ぼざろクリーチャーシリーズ 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.

update_db.py 34 KiB

2 months ago
2 months ago
2 months ago
1 month ago
1 month ago
2 months ago
2 months ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
2 months ago
2 months ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
2 months ago
2 months ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
2 months ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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. print ('Committed.')
  102. conn.close ()
  103. def update_tables (
  104. video_dao: VideoDao,
  105. tag_dao: TagDao,
  106. video_tag_dao: VideoTagDao,
  107. video_history_dao: VideoHistoryDao,
  108. comment_dao: CommentDao,
  109. user_dao: UserDao,
  110. api_data: list[VideoResult],
  111. now: datetime,
  112. ) -> None:
  113. video_ids: list[int] = []
  114. for datum in api_data:
  115. tag_names: list[str] = datum['tags'].split ()
  116. video = VideoDto (code = datum['contentId'],
  117. title = datum['title'],
  118. description = datum['description'] or '',
  119. uploaded_at = datetime.fromisoformat (datum['startTime']))
  120. video_dao.upsert (video, False)
  121. if video.id_ is not None:
  122. video_ids.append (video.id_)
  123. video_history = VideoHistoryDto (video_id = video.id_,
  124. fetched_at = now,
  125. views_count = datum['viewCounter'])
  126. video_history_dao.insert (video_history)
  127. tag_ids: list[int] = []
  128. video_tags = video_tag_dao.fetch_alive_by_video_id (video.id_, False)
  129. for vt in video_tags:
  130. tag = tag_dao.find (vt.tag_id)
  131. if (tag is not None
  132. and (tag.name not in tag_names)
  133. and (tag.id_ is not None)):
  134. tag_ids.append (tag.id_)
  135. video_tag_dao.untag_all (video.id_, tag_ids, now)
  136. tags: list[TagDto] = []
  137. for tag_name in tag_names:
  138. tag = tag_dao.fetch_by_name (tag_name)
  139. if tag is None:
  140. tag = TagDto (name = tag_name)
  141. tag_dao.insert (tag)
  142. if video.id_ is not None and tag.id_ is not None:
  143. video_tag = video_tag_dao.fetch_alive_by_ids (video.id_, tag.id_, False)
  144. if video_tag is None:
  145. video_tag = VideoTagDto (video_id = video.id_,
  146. tag_id = tag.id_,
  147. tagged_at = now)
  148. video_tag_dao.insert (video_tag, False)
  149. for com in fetch_comments (video.code):
  150. user = user_dao.fetch_by_code (com['userId'])
  151. if user is None:
  152. user = UserDto (code = com['userId'])
  153. user_dao.insert (user)
  154. if video.id_ is not None and user.id_ is not None:
  155. comment = CommentDto (video_id = video.id_,
  156. comment_no = com['no'],
  157. user_id = user.id_,
  158. content = com['body'],
  159. posted_at = datetime.fromisoformat (com['postedAt']),
  160. nico_count = com['nicoruCount'],
  161. vpos_ms = com['vposMs'])
  162. comment_dao.upsert (comment, False)
  163. alive_video_codes = [d['contentId'] for d in api_data]
  164. lost_video_ids: list[int] = []
  165. videos = video_dao.fetch_alive ()
  166. for video in videos:
  167. if video.id_ is not None and video.code not in alive_video_codes:
  168. lost_video_ids.append (video.id_)
  169. video_dao.delete (lost_video_ids, now)
  170. def fetch_comments (
  171. video_code: str,
  172. ) -> list[CommentResult]:
  173. time.sleep (1.2)
  174. headers = { 'X-Frontend-Id': '6',
  175. 'X-Frontend-Version': '0' }
  176. action_track_id = (
  177. ''.join (random.choice (string.ascii_letters + string.digits)
  178. for _ in range (10))
  179. + '_'
  180. + str (random.randrange (10 ** 12, 10 ** 13)))
  181. url = (f"https://www.nicovideo.jp/api/watch/v3_guest/{ video_code }"
  182. + f"?actionTrackId={ action_track_id }")
  183. res = requests.post (url, headers = headers, timeout = 60).json ()
  184. try:
  185. nv_comment = res['data']['comment']['nvComment']
  186. except KeyError:
  187. return []
  188. if nv_comment is None:
  189. return []
  190. headers = { 'X-Frontend-Id': '6',
  191. 'X-Frontend-Version': '0',
  192. 'Content-Type': 'application/json' }
  193. params = { 'params': nv_comment['params'],
  194. 'additionals': { },
  195. 'threadKey': nv_comment['threadKey'] }
  196. url = nv_comment['server'] + '/v1/threads'
  197. res = (requests.post (url, json.dumps (params),
  198. headers = headers,
  199. timeout = 60)
  200. .json ())
  201. try:
  202. return res['data']['threads'][1]['comments']
  203. except (IndexError, KeyError):
  204. return []
  205. def search_nico_by_tag (
  206. tag: str,
  207. ) -> list[VideoResult]:
  208. return search_nico_by_tags ([tag])
  209. def search_nico_by_tags (
  210. tags: list[str],
  211. ) -> list[VideoResult]:
  212. today = datetime.now ()
  213. url = ('https://snapshot.search.nicovideo.jp'
  214. + '/api/v2/snapshot/video/contents/search')
  215. result_data: list[VideoResult] = []
  216. to = datetime (2022, 12, 3)
  217. while to <= today:
  218. time.sleep (1.2)
  219. until = to + timedelta (days = 14)
  220. query_filter = json.dumps ({ 'type': 'or',
  221. 'filters': [
  222. { 'type': 'range',
  223. 'field': 'startTime',
  224. 'from': '%04d-%02d-%02dT00:00:00+09:00' % (to.year, to.month, to.day),
  225. 'to': '%04d-%02d-%02dT23:59:59+09:00' % (until.year, until.month, until.day),
  226. 'include_lower': True }] })
  227. params: VideoSearchParam = { 'q': ' OR '.join (tags),
  228. 'targets': 'tagsExact',
  229. '_sort': '-viewCounter',
  230. 'fields': ('contentId,'
  231. 'title,'
  232. 'tags,'
  233. 'description,'
  234. 'viewCounter,'
  235. 'startTime'),
  236. '_limit': 100,
  237. 'jsonFilter': query_filter }
  238. res = requests.get (url, params = cast (dict[str, int | str], params), timeout = 60).json ()
  239. try:
  240. result_data += res['data']
  241. except KeyError:
  242. pass
  243. to = until + timedelta (days = 1)
  244. return result_data
  245. class VideoDao:
  246. def __init__ (
  247. self,
  248. conn: MySQLConnectionAbstract,
  249. ):
  250. self.conn = conn
  251. def find (
  252. self,
  253. video_id: int,
  254. with_relation_tables: bool,
  255. ) -> VideoDto | None:
  256. with self.conn.cursor (dictionary = True) as c:
  257. print (c.execute ("""
  258. SELECT
  259. id,
  260. code,
  261. title,
  262. description,
  263. uploaded_at,
  264. deleted_at
  265. FROM
  266. videos
  267. WHERE
  268. id = %s
  269. ORDER BY
  270. id""", (video_id,)))
  271. row = cast (VideoRow | None, c.fetchone ())
  272. if row is None:
  273. return None
  274. return self._create_dto_from_row (row, with_relation_tables)
  275. def fetch_all (
  276. self,
  277. with_relation_tables: bool,
  278. ) -> list[VideoDto]:
  279. with self.conn.cursor (dictionary = True) as c:
  280. print (c.execute ("""
  281. SELECT
  282. id,
  283. code,
  284. title,
  285. description,
  286. uploaded_at,
  287. deleted_at
  288. FROM
  289. videos
  290. ORDER BY
  291. id"""))
  292. videos: list[VideoDto] = []
  293. for row in cast (list[VideoRow], c.fetchall ()):
  294. videos.append (self._create_dto_from_row (row, with_relation_tables))
  295. return videos
  296. def fetch_alive (
  297. self,
  298. ) -> list[VideoDto]:
  299. with self.conn.cursor (dictionary = True) as c:
  300. print (c.execute ("""
  301. SELECT
  302. id,
  303. code,
  304. title,
  305. description,
  306. uploaded_at,
  307. deleted_at
  308. FROM
  309. videos
  310. WHERE
  311. deleted_at IS NULL"""))
  312. videos: list[VideoDto] = []
  313. for row in cast (list[VideoRow], c.fetchall ()):
  314. videos.append (self._create_dto_from_row (row, False))
  315. return videos
  316. def upsert (
  317. self,
  318. video: VideoDto,
  319. with_relation_tables: bool,
  320. ) -> None:
  321. deleted_at: datetime | DbNullType | None = video.deleted_at
  322. if deleted_at is None:
  323. raise TypeError ('未実装')
  324. if deleted_at is DbNull:
  325. deleted_at = None
  326. deleted_at = cast (datetime | None, deleted_at)
  327. with self.conn.cursor (dictionary = True) as c:
  328. print (c.execute ("""
  329. INSERT INTO
  330. videos(
  331. code,
  332. title,
  333. description,
  334. uploaded_at,
  335. deleted_at)
  336. VALUES
  337. (
  338. %s,
  339. %s,
  340. %s,
  341. %s,
  342. %s)
  343. ON DUPLICATE KEY UPDATE
  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. print (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. print (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. print (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. print (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. print (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. print (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. video_id = VALUES(video_id),
  551. tag_id = VALUES(tag_id),
  552. tagged_at = VALUES(tagged_at),
  553. untagged_at = VALUES(untagged_at)""", (video_tag.video_id,
  554. video_tag.tag_id,
  555. video_tag.tagged_at,
  556. untagged_at)))
  557. video_tag.id_ = c.lastrowid
  558. if with_relation_tables:
  559. if video_tag.video is not None:
  560. VideoDao (self.conn).upsert (video_tag.video, True)
  561. if video_tag.tag is not None:
  562. TagDao (self.conn).upsert (video_tag.tag)
  563. def upsert_all (
  564. self,
  565. video_tags: list[VideoTagDto],
  566. with_relation_tables: bool,
  567. ) -> None:
  568. for video_tag in video_tags:
  569. self.upsert (video_tag, with_relation_tables)
  570. def untag_all (
  571. self,
  572. video_id: int,
  573. tag_ids: list[int],
  574. now: datetime,
  575. ) -> None:
  576. if not tag_ids:
  577. return
  578. with self.conn.cursor (dictionary = True) as c:
  579. print (c.execute ("""
  580. UPDATE
  581. video_tags
  582. SET
  583. untagged_at = %%s
  584. WHERE
  585. video_id = %%s
  586. AND tag_ids IN (%s)""" % ', '.join (['%s'] * len (tag_ids)), (now, video_id, *tag_ids)))
  587. def _create_dto_from_row (
  588. self,
  589. row: VideoTagRow,
  590. with_relation_tables: bool,
  591. ) -> VideoTagDto:
  592. video_tag = VideoTagDto (id_ = row['id'],
  593. video_id = row['video_id'],
  594. tag_id = row['tag_id'],
  595. tagged_at = row['tagged_at'],
  596. untagged_at = row['untagged_at'] or DbNull)
  597. if with_relation_tables:
  598. video_tag.video = VideoDao (self.conn).find (video_tag.video_id, True)
  599. video_tag.tag = TagDao (self.conn).find (video_tag.tag_id)
  600. return video_tag
  601. @dataclass (slots = True)
  602. class VideoTagDto:
  603. video_id: int
  604. tag_id: int
  605. tagged_at: date
  606. id_: int | None = None
  607. untagged_at: date | DbNullType = DbNull
  608. video: VideoDto | None = None
  609. tag: TagDto | None = None
  610. class TagDao:
  611. def __init__ (
  612. self,
  613. conn: MySQLConnectionAbstract,
  614. ):
  615. self.conn = conn
  616. def find (
  617. self,
  618. tag_id: int,
  619. ) -> TagDto | None:
  620. with self.conn.cursor (dictionary = True) as c:
  621. print (c.execute ("""
  622. SELECT
  623. id,
  624. name
  625. FROM
  626. tags
  627. WHERE
  628. id = %s""", (tag_id,)))
  629. row = cast (TagRow | None, c.fetchone ())
  630. if row is None:
  631. return None
  632. return self._create_dto_from_row (row)
  633. def fetch_by_name (
  634. self,
  635. tag_name: str,
  636. ) -> TagDto | None:
  637. with self.conn.cursor (dictionary = True) as c:
  638. print (c.execute ("""
  639. SELECT
  640. id,
  641. name
  642. FROM
  643. tags
  644. WHERE
  645. name = %s""", (tag_name,)))
  646. row = cast (TagRow | None, c.fetchone ())
  647. if row is None:
  648. return None
  649. return self._create_dto_from_row (row)
  650. def insert (
  651. self,
  652. tag: TagDto,
  653. ) -> None:
  654. with self.conn.cursor (dictionary = True) as c:
  655. print (c.execute ("""
  656. INSERT INTO
  657. tags(name)
  658. VALUES
  659. (%s)""", (tag.name,)))
  660. tag.id_ = c.lastrowid
  661. def upsert (
  662. self,
  663. tag: TagDto,
  664. ) -> None:
  665. with self.conn.cursor (dictionary = True) as c:
  666. print (c.execute ("""
  667. INSERT INTO
  668. tags(name)
  669. VALUES
  670. (%s)
  671. ON DUPLICATE KEY UPDATE
  672. name = VALUES(name)""", (tag.name,)))
  673. tag.id_ = c.lastrowid
  674. def _create_dto_from_row (
  675. self,
  676. row: TagRow,
  677. ) -> TagDto:
  678. return TagDto (id_ = row['id'],
  679. name = row['name'])
  680. @dataclass (slots = True)
  681. class TagDto:
  682. name: str
  683. id_: int | None = None
  684. class VideoHistoryDao:
  685. def __init__ (
  686. self,
  687. conn: MySQLConnectionAbstract,
  688. ):
  689. self.conn = conn
  690. def fetch_by_video_id (
  691. self,
  692. video_id: int,
  693. with_relation_tables: bool,
  694. ) -> list[VideoHistoryDto]:
  695. with self.conn.cursor (dictionary = True) as c:
  696. print (c.execute ("""
  697. SELECT
  698. id,
  699. video_id,
  700. fetched_at,
  701. views_count
  702. FROM
  703. video_histories
  704. WHERE
  705. video_id = %s""", (video_id,)))
  706. video_histories: list[VideoHistoryDto] = []
  707. for row in cast (list[VideoHistoryRow], c.fetchall ()):
  708. video_histories.append (self._create_dto_from_row (row, with_relation_tables))
  709. return video_histories
  710. def insert (
  711. self,
  712. video_history: VideoHistoryDto,
  713. ) -> None:
  714. with self.conn.cursor (dictionary = True) as c:
  715. print (c.execute ("""
  716. INSERT INTO
  717. video_histories(
  718. video_id,
  719. fetched_at,
  720. views_count)
  721. VALUES
  722. (
  723. %s,
  724. %s,
  725. %s)""", (video_history.video_id,
  726. video_history.fetched_at,
  727. video_history.views_count)))
  728. def upsert (
  729. self,
  730. video_history: VideoHistoryDto,
  731. ) -> None:
  732. with self.conn.cursor (dictionary = True) as c:
  733. print (c.execute ("""
  734. INSERT INTO
  735. video_histories(
  736. video_id,
  737. fetched_at,
  738. views_count)
  739. VALUES
  740. (
  741. %s,
  742. %s,
  743. %s)
  744. ON DUPLICATE KEY UPDATE
  745. video_id,
  746. fetched_at,
  747. views_count""", (video_history.video_id,
  748. video_history.fetched_at,
  749. video_history.views_count)))
  750. def upsert_all (
  751. self,
  752. video_histories: list[VideoHistoryDto],
  753. ) -> None:
  754. for video_history in video_histories:
  755. self.upsert (video_history)
  756. def _create_dto_from_row (
  757. self,
  758. row: VideoHistoryRow,
  759. with_relation_tables: bool,
  760. ) -> VideoHistoryDto:
  761. video_history = VideoHistoryDto (id_ = row['id'],
  762. video_id = row['video_id'],
  763. fetched_at = row['fetched_at'],
  764. views_count = row['views_count'])
  765. if with_relation_tables:
  766. video_history.video = VideoDao (self.conn).find (video_history.video_id, True)
  767. return video_history
  768. @dataclass (slots = True)
  769. class VideoHistoryDto:
  770. video_id: int
  771. fetched_at: date
  772. views_count: int
  773. id_: int | None = None
  774. video: VideoDto | None = None
  775. class CommentDao:
  776. def __init__ (
  777. self,
  778. conn: MySQLConnectionAbstract,
  779. ):
  780. self.conn = conn
  781. def fetch_by_video_id (
  782. self,
  783. video_id: int,
  784. with_relation_tables: bool,
  785. ) -> list[CommentDto]:
  786. with self.conn.cursor (dictionary = True) as c:
  787. print (c.execute ("""
  788. SELECT
  789. id,
  790. video_id,
  791. comment_no,
  792. user_id,
  793. content,
  794. posted_at,
  795. nico_count,
  796. vpos_ms
  797. FROM
  798. comments
  799. WHERE
  800. video_id = %s""", (video_id,)))
  801. comments: list[CommentDto] = []
  802. for row in cast (list[CommentRow], c.fetchall ()):
  803. comments.append (self._create_dto_from_row (row, with_relation_tables))
  804. return comments
  805. def upsert (
  806. self,
  807. comment: CommentDto,
  808. with_relation_tables: bool,
  809. ) -> None:
  810. vpos_ms: int | DbNullType | None = comment.vpos_ms
  811. if vpos_ms is None:
  812. raise TypeError ('未実装')
  813. if vpos_ms is DbNull:
  814. vpos_ms = None
  815. vpos_ms = cast (int | None, vpos_ms)
  816. with self.conn.cursor (dictionary = True) as c:
  817. print (c.execute ("""
  818. INSERT INTO
  819. comments(
  820. video_id,
  821. comment_no,
  822. user_id,
  823. content,
  824. posted_at,
  825. nico_count,
  826. vpos_ms)
  827. VALUES
  828. (
  829. %s,
  830. %s,
  831. %s,
  832. %s,
  833. %s,
  834. %s,
  835. %s)
  836. ON DUPLICATE KEY UPDATE
  837. video_id = VALUES(video_id),
  838. comment_no = VALUES(comment_no),
  839. user_id = VALUES(user_id),
  840. content = VALUES(content),
  841. posted_at = VALUES(posted_at),
  842. nico_count = VALUES(nico_count),
  843. vpos_ms = VALUES(vpos_ms)""", (comment.video_id,
  844. comment.comment_no,
  845. comment.user_id,
  846. comment.content,
  847. comment.posted_at,
  848. comment.nico_count,
  849. vpos_ms)))
  850. def upsert_all (
  851. self,
  852. comments: list[CommentDto],
  853. with_relation_tables: bool,
  854. ) -> None:
  855. for comment in comments:
  856. self.upsert (comment, with_relation_tables)
  857. def _create_dto_from_row (
  858. self,
  859. row: CommentRow,
  860. with_relation_tables: bool,
  861. ) -> CommentDto:
  862. comment = CommentDto (id_ = row['id'],
  863. video_id = row['video_id'],
  864. comment_no = row['comment_no'],
  865. user_id = row['user_id'],
  866. content = row['content'],
  867. posted_at = row['posted_at'],
  868. nico_count = row['nico_count'],
  869. vpos_ms = row['vpos_ms'] or DbNull)
  870. if with_relation_tables:
  871. comment.video = VideoDao (self.conn).find (comment.video_id, True)
  872. return comment
  873. @dataclass (slots = True)
  874. class CommentDto:
  875. video_id: int
  876. comment_no: int
  877. user_id: int
  878. content: str
  879. posted_at: datetime
  880. id_: int | None = None
  881. nico_count: int = 0
  882. vpos_ms: int | DbNullType = DbNull
  883. video: VideoDto | None = None
  884. user: UserDto | None = None
  885. class UserDao:
  886. def __init__ (
  887. self,
  888. conn: MySQLConnectionAbstract,
  889. ):
  890. self.conn = conn
  891. def fetch_by_code (
  892. self,
  893. user_code: str
  894. ) -> UserDto | None:
  895. with self.conn.cursor (dictionary = True) as c:
  896. print (c.execute ("""
  897. SELECT
  898. id,
  899. code
  900. FROM
  901. users
  902. WHERE
  903. code = %s""", (user_code,)))
  904. row = cast (UserRow | None, c.fetchone ())
  905. if row is None:
  906. return None
  907. return self._create_dto_from_row (row)
  908. def insert (
  909. self,
  910. user: UserDto,
  911. ) -> None:
  912. with self.conn.cursor (dictionary = True) as c:
  913. print (c.execute ("""
  914. INSERT INTO
  915. users(code)
  916. VALUES
  917. (%s)""", (user.code,)))
  918. user.id_ = c.lastrowid
  919. def _create_dto_from_row (
  920. self,
  921. row: UserRow,
  922. ) -> UserDto:
  923. return UserDto (id_ = row['id'],
  924. code = row['code'])
  925. @dataclass (slots = True)
  926. class UserDto:
  927. code: str
  928. id_: int | None = None
  929. if __name__ == '__main__':
  930. main ()