cookies.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2020 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from typing import Optional
  17. from http.cookies import Morsel, SimpleCookie
  18. from aiohttp import CookieJar
  19. from yarl import URL
  20. from mautrix.types import Serializable, JSON
  21. from ..errors import IGCookieNotFoundError
  22. ig_url = URL("https://instagram.com")
  23. class Cookies(Serializable):
  24. jar: CookieJar
  25. def __init__(self) -> None:
  26. self.jar = CookieJar()
  27. def serialize(self) -> JSON:
  28. return {
  29. morsel.key: {
  30. **{k: v for k, v in morsel.items() if v},
  31. "value": morsel.value,
  32. } for morsel in self.jar
  33. }
  34. @classmethod
  35. def deserialize(cls, raw: JSON) -> 'Cookies':
  36. cookie = SimpleCookie()
  37. for key, data in raw.items():
  38. cookie[key] = data.pop("value")
  39. cookie[key].update(data)
  40. cookies = cls()
  41. cookies.jar.update_cookies(cookie, ig_url)
  42. return cookies
  43. @property
  44. def csrf_token(self) -> str:
  45. try:
  46. return self["csrftoken"]
  47. except IGCookieNotFoundError:
  48. return "missing"
  49. @property
  50. def user_id(self) -> str:
  51. return self["ds_user_id"]
  52. @property
  53. def username(self) -> str:
  54. return self["ds_username"]
  55. def get(self, key: str) -> Morsel:
  56. filtered = self.jar.filter_cookies(ig_url)
  57. return filtered.get(key)
  58. def get_value(self, key: str) -> Optional[str]:
  59. cookie = self.get(key)
  60. return cookie.value if cookie else None
  61. def __getitem__(self, key: str) -> str:
  62. cookie = self.get(key)
  63. if not cookie:
  64. raise IGCookieNotFoundError(key)
  65. return cookie.value