upload.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2022 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 __future__ import annotations
  17. from uuid import uuid4
  18. import random
  19. import time
  20. import json
  21. from .base import BaseAndroidAPI
  22. from ..types import UploadPhotoResponse, UploadVideoResponse, FinishUploadResponse, MediaType
  23. class UploadAPI(BaseAndroidAPI):
  24. async def upload_photo(
  25. self,
  26. data: bytes,
  27. mime: str,
  28. upload_id: str | None = None,
  29. width: int | None = None,
  30. height: int | None = None,
  31. ) -> UploadPhotoResponse:
  32. upload_id = upload_id or str(int(time.time() * 1000))
  33. name = f"{upload_id}_0_{random.randint(1000000000, 9999999999)}"
  34. params = {
  35. "retry_context": json.dumps({
  36. "num_step_auto_retry": 0,
  37. "num_reupload": 0,
  38. "num_step_manual_retry": 0,
  39. }),
  40. "media_type": str(MediaType.IMAGE.value),
  41. "upload_id": upload_id,
  42. "xsharing_user_ids": json.dumps([]),
  43. }
  44. if mime == "image/jpeg":
  45. params["image_compression"] = json.dumps({
  46. "lib_name": "moz",
  47. "lib_version": "3.1.m",
  48. "quality": 80
  49. })
  50. if width and height:
  51. params["original_width"] = str(width)
  52. params["original_height"] = str(height)
  53. headers = {
  54. "X_FB_PHOTO_WATERFALL_ID": str(uuid4()),
  55. "X-Entity-Type": mime,
  56. "Offset": "0",
  57. "X-Instagram-Rupload-Params": json.dumps(params),
  58. "X-Entity-Name": name,
  59. "X-Entity-Length": str(len(data)),
  60. "Content-Type": "application/octet-stream",
  61. "priority": "u=6, i",
  62. }
  63. return await self.std_http_post(f"/rupload_igphoto/{name}", headers=headers, data=data,
  64. raw=True, response_type=UploadPhotoResponse)
  65. async def upload_mp4(
  66. self,
  67. data: bytes,
  68. upload_id: str | None = None,
  69. audio: bool = False,
  70. duration_ms: int | None = None,
  71. width: int | None = None,
  72. height: int | None = None,
  73. ) -> tuple[UploadVideoResponse, str]:
  74. upload_id = upload_id or str(int(time.time() * 1000))
  75. name = f"{upload_id}_0_{random.randint(1000000000, 9999999999)}"
  76. media_type = MediaType.AUDIO if audio else MediaType.VIDEO
  77. params: dict[str, str] = {
  78. "retry_context": json.dumps({
  79. "num_step_auto_retry": 0,
  80. "num_reupload": 0,
  81. "num_step_manual_retry": 0,
  82. }),
  83. "media_type": str(media_type.value),
  84. "upload_id": upload_id,
  85. "xsharing_user_ids": json.dumps([]),
  86. }
  87. if duration_ms:
  88. params["upload_media_duration_ms"] = str(duration_ms)
  89. if audio:
  90. params["is_direct_voice"] = "1"
  91. else:
  92. params["direct_v2"] = "1"
  93. params["for_direct_story"] = "1"
  94. params["content_tags"] = "use_default_cover"
  95. params["extract_cover_frame"] = "1"
  96. if width and height:
  97. params["upload_media_width"] = str(width)
  98. params["upload_media_height"] = str(height)
  99. headers = {
  100. "X_FB_VIDEO_WATERFALL_ID": str(uuid4()),
  101. "X-Entity-Type": "audio/mp4" if audio else "video/mp4",
  102. "Offset": "0",
  103. "X-Instagram-Rupload-Params": json.dumps(params),
  104. "X-Entity-Name": name,
  105. "X-Entity-Length": str(len(data)),
  106. "Content-Type": "application/octet-stream",
  107. "priority": "u=6, i",
  108. }
  109. if not audio:
  110. headers["segment-type"] = "3"
  111. headers["segment-start-offset"] = "0"
  112. return await self.std_http_post(f"/rupload_igvideo/{name}", headers=headers, data=data,
  113. raw=True, response_type=UploadVideoResponse), upload_id
  114. async def finish_upload(
  115. self, upload_id: str, source_type: str, video: bool = False
  116. ) -> FinishUploadResponse:
  117. headers = {
  118. "retry_context": json.dumps({
  119. "num_step_auto_retry": 0,
  120. "num_reupload": 0,
  121. "num_step_manual_retry": 0,
  122. }),
  123. }
  124. req = {
  125. "timezone_offset": self.state.device.timezone_offset,
  126. "_csrftoken": self.state.cookies.csrf_token,
  127. "source_type": source_type,
  128. "_uid": self.state.cookies.user_id,
  129. "device_id": self.state.device.id,
  130. "_uuid": self.state.device.uuid,
  131. "upload_id": upload_id,
  132. "device": self.state.device.payload,
  133. }
  134. query = {}
  135. if video:
  136. query["video"] = "1"
  137. return await self.std_http_post("/api/v1/media/upload_finish/", headers=headers, data=req,
  138. query=query, response_type=FinishUploadResponse)