oauth_data_source.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import datetime
  2. import urllib.parse
  3. from typing import Any
  4. import requests
  5. from flask_login import current_user # type: ignore
  6. from extensions.ext_database import db
  7. from models.source import DataSourceOauthBinding
  8. class OAuthDataSource:
  9. def __init__(self, client_id: str, client_secret: str, redirect_uri: str):
  10. self.client_id = client_id
  11. self.client_secret = client_secret
  12. self.redirect_uri = redirect_uri
  13. def get_authorization_url(self):
  14. raise NotImplementedError()
  15. def get_access_token(self, code: str):
  16. raise NotImplementedError()
  17. class NotionOAuth(OAuthDataSource):
  18. _AUTH_URL = "https://api.notion.com/v1/oauth/authorize"
  19. _TOKEN_URL = "https://api.notion.com/v1/oauth/token"
  20. _NOTION_PAGE_SEARCH = "https://api.notion.com/v1/search"
  21. _NOTION_BLOCK_SEARCH = "https://api.notion.com/v1/blocks"
  22. _NOTION_BOT_USER = "https://api.notion.com/v1/users/me"
  23. def get_authorization_url(self):
  24. params = {
  25. "client_id": self.client_id,
  26. "response_type": "code",
  27. "redirect_uri": self.redirect_uri,
  28. "owner": "user",
  29. }
  30. return f"{self._AUTH_URL}?{urllib.parse.urlencode(params)}"
  31. def get_access_token(self, code: str):
  32. data = {"code": code, "grant_type": "authorization_code", "redirect_uri": self.redirect_uri}
  33. headers = {"Accept": "application/json"}
  34. auth = (self.client_id, self.client_secret)
  35. response = requests.post(self._TOKEN_URL, data=data, auth=auth, headers=headers)
  36. response_json = response.json()
  37. access_token = response_json.get("access_token")
  38. if not access_token:
  39. raise ValueError(f"Error in Notion OAuth: {response_json}")
  40. workspace_name = response_json.get("workspace_name")
  41. workspace_icon = response_json.get("workspace_icon")
  42. workspace_id = response_json.get("workspace_id")
  43. # get all authorized pages
  44. pages = self.get_authorized_pages(access_token)
  45. source_info = {
  46. "workspace_name": workspace_name,
  47. "workspace_icon": workspace_icon,
  48. "workspace_id": workspace_id,
  49. "pages": pages,
  50. "total": len(pages),
  51. }
  52. # save data source binding
  53. data_source_binding = DataSourceOauthBinding.query.filter(
  54. db.and_(
  55. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  56. DataSourceOauthBinding.provider == "notion",
  57. DataSourceOauthBinding.access_token == access_token,
  58. )
  59. ).first()
  60. if data_source_binding:
  61. data_source_binding.source_info = source_info
  62. data_source_binding.disabled = False
  63. data_source_binding.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  64. db.session.commit()
  65. else:
  66. new_data_source_binding = DataSourceOauthBinding(
  67. tenant_id=current_user.current_tenant_id,
  68. access_token=access_token,
  69. source_info=source_info,
  70. provider="notion",
  71. )
  72. db.session.add(new_data_source_binding)
  73. db.session.commit()
  74. def save_internal_access_token(self, access_token: str):
  75. workspace_name = self.notion_workspace_name(access_token)
  76. workspace_icon = None
  77. workspace_id = current_user.current_tenant_id
  78. # get all authorized pages
  79. pages = self.get_authorized_pages(access_token)
  80. source_info = {
  81. "workspace_name": workspace_name,
  82. "workspace_icon": workspace_icon,
  83. "workspace_id": workspace_id,
  84. "pages": pages,
  85. "total": len(pages),
  86. }
  87. # save data source binding
  88. data_source_binding = DataSourceOauthBinding.query.filter(
  89. db.and_(
  90. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  91. DataSourceOauthBinding.provider == "notion",
  92. DataSourceOauthBinding.access_token == access_token,
  93. )
  94. ).first()
  95. if data_source_binding:
  96. data_source_binding.source_info = source_info
  97. data_source_binding.disabled = False
  98. data_source_binding.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  99. db.session.commit()
  100. else:
  101. new_data_source_binding = DataSourceOauthBinding(
  102. tenant_id=current_user.current_tenant_id,
  103. access_token=access_token,
  104. source_info=source_info,
  105. provider="notion",
  106. )
  107. db.session.add(new_data_source_binding)
  108. db.session.commit()
  109. def sync_data_source(self, binding_id: str):
  110. # save data source binding
  111. data_source_binding = DataSourceOauthBinding.query.filter(
  112. db.and_(
  113. DataSourceOauthBinding.tenant_id == current_user.current_tenant_id,
  114. DataSourceOauthBinding.provider == "notion",
  115. DataSourceOauthBinding.id == binding_id,
  116. DataSourceOauthBinding.disabled == False,
  117. )
  118. ).first()
  119. if data_source_binding:
  120. # get all authorized pages
  121. pages = self.get_authorized_pages(data_source_binding.access_token)
  122. source_info = data_source_binding.source_info
  123. new_source_info = {
  124. "workspace_name": source_info["workspace_name"],
  125. "workspace_icon": source_info["workspace_icon"],
  126. "workspace_id": source_info["workspace_id"],
  127. "pages": pages,
  128. "total": len(pages),
  129. }
  130. data_source_binding.source_info = new_source_info
  131. data_source_binding.disabled = False
  132. data_source_binding.updated_at = datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
  133. db.session.commit()
  134. else:
  135. raise ValueError("Data source binding not found")
  136. def get_authorized_pages(self, access_token: str):
  137. pages = []
  138. page_results = self.notion_page_search(access_token)
  139. database_results = self.notion_database_search(access_token)
  140. # get page detail
  141. for page_result in page_results:
  142. page_id = page_result["id"]
  143. page_name = "Untitled"
  144. for key in page_result["properties"]:
  145. if "title" in page_result["properties"][key] and page_result["properties"][key]["title"]:
  146. title_list = page_result["properties"][key]["title"]
  147. if len(title_list) > 0 and "plain_text" in title_list[0]:
  148. page_name = title_list[0]["plain_text"]
  149. page_icon = page_result["icon"]
  150. if page_icon:
  151. icon_type = page_icon["type"]
  152. if icon_type in {"external", "file"}:
  153. url = page_icon[icon_type]["url"]
  154. icon = {"type": "url", "url": url if url.startswith("http") else f"https://www.notion.so{url}"}
  155. else:
  156. icon = {"type": "emoji", "emoji": page_icon[icon_type]}
  157. else:
  158. icon = None
  159. parent = page_result["parent"]
  160. parent_type = parent["type"]
  161. if parent_type == "block_id":
  162. parent_id = self.notion_block_parent_page_id(access_token, parent[parent_type])
  163. elif parent_type == "workspace":
  164. parent_id = "root"
  165. else:
  166. parent_id = parent[parent_type]
  167. page = {
  168. "page_id": page_id,
  169. "page_name": page_name,
  170. "page_icon": icon,
  171. "parent_id": parent_id,
  172. "type": "page",
  173. }
  174. pages.append(page)
  175. # get database detail
  176. for database_result in database_results:
  177. page_id = database_result["id"]
  178. if len(database_result["title"]) > 0:
  179. page_name = database_result["title"][0]["plain_text"]
  180. else:
  181. page_name = "Untitled"
  182. page_icon = database_result["icon"]
  183. if page_icon:
  184. icon_type = page_icon["type"]
  185. if icon_type in {"external", "file"}:
  186. url = page_icon[icon_type]["url"]
  187. icon = {"type": "url", "url": url if url.startswith("http") else f"https://www.notion.so{url}"}
  188. else:
  189. icon = {"type": icon_type, icon_type: page_icon[icon_type]}
  190. else:
  191. icon = None
  192. parent = database_result["parent"]
  193. parent_type = parent["type"]
  194. if parent_type == "block_id":
  195. parent_id = self.notion_block_parent_page_id(access_token, parent[parent_type])
  196. elif parent_type == "workspace":
  197. parent_id = "root"
  198. else:
  199. parent_id = parent[parent_type]
  200. page = {
  201. "page_id": page_id,
  202. "page_name": page_name,
  203. "page_icon": icon,
  204. "parent_id": parent_id,
  205. "type": "database",
  206. }
  207. pages.append(page)
  208. return pages
  209. def notion_page_search(self, access_token: str):
  210. results = []
  211. next_cursor = None
  212. has_more = True
  213. while has_more:
  214. data: dict[str, Any] = {
  215. "filter": {"value": "page", "property": "object"},
  216. **({"start_cursor": next_cursor} if next_cursor else {}),
  217. }
  218. headers = {
  219. "Content-Type": "application/json",
  220. "Authorization": f"Bearer {access_token}",
  221. "Notion-Version": "2022-06-28",
  222. }
  223. response = requests.post(url=self._NOTION_PAGE_SEARCH, json=data, headers=headers)
  224. response_json = response.json()
  225. results.extend(response_json.get("results", []))
  226. has_more = response_json.get("has_more", False)
  227. next_cursor = response_json.get("next_cursor", None)
  228. return results
  229. def notion_block_parent_page_id(self, access_token: str, block_id: str):
  230. headers = {
  231. "Authorization": f"Bearer {access_token}",
  232. "Notion-Version": "2022-06-28",
  233. }
  234. response = requests.get(url=f"{self._NOTION_BLOCK_SEARCH}/{block_id}", headers=headers)
  235. response_json = response.json()
  236. if response.status_code != 200:
  237. message = response_json.get("message", "unknown error")
  238. raise ValueError(f"Error fetching block parent page ID: {message}")
  239. parent = response_json["parent"]
  240. parent_type = parent["type"]
  241. if parent_type == "block_id":
  242. return self.notion_block_parent_page_id(access_token, parent[parent_type])
  243. return parent[parent_type]
  244. def notion_workspace_name(self, access_token: str):
  245. headers = {
  246. "Authorization": f"Bearer {access_token}",
  247. "Notion-Version": "2022-06-28",
  248. }
  249. response = requests.get(url=self._NOTION_BOT_USER, headers=headers)
  250. response_json = response.json()
  251. if "object" in response_json and response_json["object"] == "user":
  252. user_type = response_json["type"]
  253. user_info = response_json[user_type]
  254. if "workspace_name" in user_info:
  255. return user_info["workspace_name"]
  256. return "workspace"
  257. def notion_database_search(self, access_token: str):
  258. results = []
  259. next_cursor = None
  260. has_more = True
  261. while has_more:
  262. data: dict[str, Any] = {
  263. "filter": {"value": "database", "property": "object"},
  264. **({"start_cursor": next_cursor} if next_cursor else {}),
  265. }
  266. headers = {
  267. "Content-Type": "application/json",
  268. "Authorization": f"Bearer {access_token}",
  269. "Notion-Version": "2022-06-28",
  270. }
  271. response = requests.post(url=self._NOTION_PAGE_SEARCH, json=data, headers=headers)
  272. response_json = response.json()
  273. results.extend(response_json.get("results", []))
  274. has_more = response_json.get("has_more", False)
  275. next_cursor = response_json.get("next_cursor", None)
  276. return results