Add fetchThreadImages (#434)

This commit is contained in:
Przemek
2019-07-24 13:40:00 +02:00
committed by Mads Marquart
parent 1b08243cd2
commit 700cf14a50
3 changed files with 67 additions and 0 deletions

View File

@@ -1,5 +1,6 @@
# -*- coding: UTF-8 -*-
from itertools import islice
from fbchat import Client
from fbchat.models import *
@@ -62,3 +63,9 @@ print("thread's type: {}".format(thread.type))
# Here should be an example of `getUnread`
# Print image url for 20 last images from thread.
images = client.fetchThreadImages("<thread id>")
for image in islice(image, 20):
print(image.large_preview_url)

View File

@@ -981,6 +981,42 @@ class Client(object):
"""
return self._buddylist.get(str(user_id))
def fetchThreadImages(self, thread_id=None):
"""
Creates generator object for fetching images posted in thread.
:param thread_id: ID of the thread
:return: :class:`ImageAttachment` or :class:`VideoAttachment`.
:rtype: iterable
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"id": thread_id, "first": 48}
thread_id = str(thread_id)
j = self.graphql_request(_graphql.from_query_id("515216185516880", data))
while True:
try:
i = j[thread_id]["message_shared_media"]["edges"][0]
except IndexError:
if j[thread_id]["message_shared_media"]["page_info"].get(
"has_next_page"
):
data["after"] = j[thread_id]["message_shared_media"][
"page_info"
].get("end_cursor")
j = self.graphql_request(
_graphql.from_query_id("515216185516880", data)
)
continue
else:
break
if i["node"].get("__typename") == "MessageImage":
yield ImageAttachment._from_list(i)
elif i["node"].get("__typename") == "MessageVideo":
yield VideoAttachment._from_list(i)
else:
yield Attachment(uid=i["node"].get("legacy_attachment_id"))
del j[thread_id]["message_shared_media"]["edges"][0]
"""
END FETCH METHODS
"""

View File

@@ -155,6 +155,18 @@ class ImageAttachment(Attachment):
uid=data.get("legacy_attachment_id"),
)
@classmethod
def _from_list(cls, data):
data = data["node"]
return cls(
width=data["original_dimensions"].get("x"),
height=data["original_dimensions"].get("y"),
thumbnail_url=data["image"].get("uri"),
large_preview=data["image2"],
preview=data["image1"],
uid=data["legacy_attachment_id"],
)
@attr.s(cmp=False, init=False)
class VideoAttachment(Attachment):
@@ -252,6 +264,18 @@ class VideoAttachment(Attachment):
uid=data["target"].get("video_id"),
)
@classmethod
def _from_list(cls, data):
data = data["node"]
return cls(
width=data["original_dimensions"].get("x"),
height=data["original_dimensions"].get("y"),
small_image=data["image"],
medium_image=data["image1"],
large_image=data["image2"],
uid=data["legacy_attachment_id"],
)
def graphql_to_attachment(data):
_type = data["__typename"]