Просмотр исходного кода

Use same aiohttp instance for fetching avatar so proxies work

Tulir Asokan 4 лет назад
Родитель
Сommit
4a7cea14e7
4 измененных файлов с 19 добавлено и 23 удалено
  1. 3 4
      mauigpapi/http/base.py
  2. 10 11
      mautrix_instagram/portal.py
  3. 5 7
      mautrix_instagram/puppet.py
  4. 1 1
      mautrix_instagram/user.py

+ 3 - 4
mauigpapi/http/base.py

@@ -13,7 +13,7 @@
 #
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
-from typing import Optional, Dict, Any, TypeVar, Type
+from typing import Optional, Dict, Any, TypeVar, Type, Union
 import random
 import time
 import json
@@ -93,11 +93,10 @@ class BaseAndroidAPI:
         }
         return {k: v for k, v in headers.items() if v is not None}
 
-    async def raw_http_get(self, url: URL) -> ClientResponse:
-        return await self.http.get(url, headers={
+    def raw_http_get(self, url: Union[URL, str]):
+        return self.http.get(url, headers={
             "user-agent": self.state.user_agent,
             "accept-language": self.state.device.language.replace("_", "-"),
-            "authorization": self.state.session.authorization,
         })
 
     async def std_http_post(self, path: str, data: Optional[JSON] = None, raw: bool = False,

+ 10 - 11
mautrix_instagram/portal.py

@@ -21,7 +21,6 @@ import mimetypes
 import asyncio
 
 import magic
-from yarl import URL
 
 from mauigpapi.types import (Thread, ThreadUser, ThreadItem, RegularMediaItem, MediaType,
                              ReactionStatus, Reaction, AnimatedMediaItem, ThreadItemType)
@@ -273,9 +272,9 @@ class Portal(DBPortal, BasePortal):
     async def _reupload_instagram_file(self, source: 'u.User', url: str, msgtype: MessageType,
                                        info: FileInfo, intent: IntentAPI
                                        ) -> Optional[ReuploadedMediaInfo]:
-        resp = await source.client.raw_http_get(URL(url))
-        data = await resp.read()
-        info.mime_type = resp.headers["Content-Type"] or magic.from_buffer(data, mime=True)
+        async with await source.client.raw_http_get(url) as resp:
+            data = await resp.read()
+            info.mime_type = resp.headers["Content-Type"] or magic.from_buffer(data, mime=True)
         info.size = len(data)
         extension = {
             "image/webp": ".webp",
@@ -405,12 +404,12 @@ class Portal(DBPortal, BasePortal):
     # endregion
     # region Updating portal info
 
-    async def update_info(self, thread: Thread) -> None:
+    async def update_info(self, thread: Thread, source: 'u.User') -> None:
         changed = await self._update_name(thread.thread_title)
         if changed:
             await self.update_bridge_info()
             await self.update()
-        await self._update_participants(thread.users)
+        await self._update_participants(thread.users, source)
         # TODO update power levels with thread.admin_user_ids
 
     async def _update_name(self, name: str) -> bool:
@@ -421,14 +420,14 @@ class Portal(DBPortal, BasePortal):
             return True
         return False
 
-    async def _update_participants(self, users: List[ThreadUser]) -> None:
+    async def _update_participants(self, users: List[ThreadUser], source: 'u.User') -> None:
         if not self.mxid:
             return
 
         # Make sure puppets who should be here are here
         for user in users:
             puppet = await p.Puppet.get_by_pk(user.pk)
-            await puppet.update_info(user)
+            await puppet.update_info(user, source)
             await puppet.intent_for(self).ensure_joined(self.mxid)
 
         # Kick puppets who shouldn't be here
@@ -549,7 +548,7 @@ class Portal(DBPortal, BasePortal):
             if did_join and self.is_direct:
                 await source.update_direct_chats({self.main_intent.mxid: [self.mxid]})
 
-        await self.update_info(info)
+        await self.update_info(info, source)
 
         if backfill:
             last_msg = await DBMessage.get_by_item_id(info.last_permanent_item.item_id,
@@ -573,7 +572,7 @@ class Portal(DBPortal, BasePortal):
         if self.mxid:
             await self.update_matrix_room(source, info)
             return self.mxid
-        await self.update_info(info)
+        await self.update_info(info, source)
         self.log.debug("Creating Matrix room")
         name: Optional[str] = None
         initial_state = [{
@@ -623,7 +622,7 @@ class Portal(DBPortal, BasePortal):
             self.log.debug(f"Matrix room created: {self.mxid}")
             self.by_mxid[self.mxid] = self
             if not self.is_direct:
-                await self._update_participants(info.users)
+                await self._update_participants(info.users, source)
 
             puppet = await p.Puppet.get_by_custom_mxid(source.mxid)
             if puppet:

+ 5 - 7
mautrix_instagram/puppet.py

@@ -26,7 +26,7 @@ from mautrix.util.simple_template import SimpleTemplate
 
 from .db import Puppet as DBPuppet
 from .config import Config
-from . import portal as p
+from . import portal as p, user as u
 
 if TYPE_CHECKING:
     from .__main__ import InstagramBridge
@@ -89,10 +89,10 @@ class Puppet(DBPuppet, BasePuppet):
         return (portal.other_user_pk != self.pk and self.is_real_user
                 and self.config["bridge.backfill.invite_own_puppet"])
 
-    async def update_info(self, info: BaseResponseUser) -> None:
+    async def update_info(self, info: BaseResponseUser, source: 'u.User') -> None:
         update = False
         update = await self._update_name(info) or update
-        update = await self._update_avatar(info) or update
+        update = await self._update_avatar(info, source) or update
         if update:
             await self.update()
 
@@ -114,13 +114,11 @@ class Puppet(DBPuppet, BasePuppet):
             return True
         return False
 
-    async def _update_avatar(self, info: BaseResponseUser) -> bool:
+    async def _update_avatar(self, info: BaseResponseUser, source: 'u.User') -> bool:
         if info.profile_pic_id != self.photo_id or not self.avatar_set:
             self.photo_id = info.profile_pic_id
             if info.profile_pic_id:
-                # TODO if info.has_anonymous_profile_picture, we might need auth to get it
-                #      ...and we should probably download it with the device headers anyway
-                async with ClientSession() as sess, sess.get(info.profile_pic_url) as resp:
+                async with source.client.raw_http_get(info.profile_pic_url) as resp:
                     content_type = resp.headers["Content-Type"]
                     resp_data = await resp.read()
                 mxc = await self.default_mxid_intent.upload_media(data=resp_data,

+ 1 - 1
mautrix_instagram/user.py

@@ -162,7 +162,7 @@ class User(DBUser, BaseUser):
     async def _try_sync_puppet(self, user_info: CurrentUser) -> None:
         puppet = await pu.Puppet.get_by_pk(self.igpk)
         try:
-            await puppet.update_info(user_info)
+            await puppet.update_info(user_info, self)
         except Exception:
             self.log.exception("Failed to update own puppet info")
         try: