upload.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. import random
  18. import time
  19. from yarl import URL
  20. from ..types import FacebookUploadResponse
  21. from .base import BaseAndroidAPI
  22. class UploadAPI(BaseAndroidAPI):
  23. rupload_fb = URL("https://rupload.facebook.com")
  24. def _make_rupload_headers(self, length: int, name: str, mime: str) -> dict[str, str]:
  25. return {
  26. **self._rupload_headers,
  27. "x-entity-length": str(length),
  28. "x-entity-name": name,
  29. "x-entity-type": mime,
  30. "offset": "0",
  31. "Content-Type": "application/octet-stream",
  32. "priority": "u=6, i",
  33. }
  34. async def upload(
  35. self,
  36. data: bytes,
  37. mimetype: str,
  38. upload_id: str | None = None,
  39. ) -> FacebookUploadResponse:
  40. upload_id = upload_id or str(int(time.time() * 1000))
  41. name = f"{upload_id}_0_{random.randint(1000000000, 9999999999)}"
  42. headers = self._make_rupload_headers(len(data), name, mimetype)
  43. if mimetype.startswith("image/"):
  44. path_type = "messenger_gif" if mimetype == "image/gif" else "messenger_image"
  45. headers["image_type"] = "FILE_ATTACHMENT"
  46. elif mimetype.startswith("video/"):
  47. path_type = "messenger_video"
  48. headers["video_type"] = "FILE_ATTACHMENT"
  49. elif mimetype.startswith("audio/"):
  50. path_type = "messenger_audio"
  51. headers["audio_type"] = "VOICE_MESSAGE"
  52. else:
  53. path_type = "messenger_file"
  54. headers["file_type"] = "FILE_ATTACHMENT"
  55. return await self.std_http_post(
  56. f"/{path_type}/{name}",
  57. url_override=self.rupload_fb,
  58. default_headers=False,
  59. headers=headers,
  60. data=data,
  61. raw=True,
  62. response_type=FacebookUploadResponse,
  63. )