Merge pull request #498 from carpedm20/rename-uid

Rename .uid to .id
This commit is contained in:
Mads Marquart
2020-01-09 10:58:46 +01:00
committed by GitHub
35 changed files with 208 additions and 197 deletions

View File

@@ -8,7 +8,7 @@ class Attachment:
"""Represents a Facebook attachment."""
#: The attachment ID
uid = attr.ib(None)
id = attr.ib(None)
@attrs_default
@@ -56,7 +56,7 @@ class ShareAttachment(Attachment):
url = data.get("url")
return cls(
uid=data.get("deduplication_key"),
id=data.get("deduplication_key"),
author=data["target"]["actors"][0]["id"]
if data["target"].get("actors")
else None,

View File

@@ -43,24 +43,11 @@ class Client:
useful while listening).
"""
@property
def uid(self):
"""The ID of the client.
Can be used as ``thread_id``. See :ref:`intro_threads` for more info.
"""
return self._uid
def __init__(self, session):
"""Initialize and log in the client.
"""Initialize the client model.
Args:
email: Facebook ``email``, ``id`` or ``phone number``
password: Facebook account password
session_cookies (dict): Cookies from a previous session (Will default to login if these are invalid)
Raises:
FBchatException: On failed login
session: The session to use when making requests.
"""
self._sticky, self._pool = (None, None)
self._seq = "0"
@@ -68,7 +55,11 @@ class Client:
self._mark_alive = True
self._buddylist = dict()
self._session = session
self._uid = session.user_id
@property
def session(self):
"""The session that's used when making requests."""
return self._session
def __repr__(self):
return "Client(session={!r})".format(self._session)
@@ -195,12 +186,12 @@ class Client:
users_to_fetch = [] # It's more efficient to fetch all users in one request
for thread in threads:
if thread.type == ThreadType.USER:
if thread.uid not in [user.uid for user in users]:
if thread.id not in [user.id for user in users]:
users.append(thread)
elif thread.type == ThreadType.GROUP:
for user_id in thread.participants:
if (
user_id not in [user.uid for user in users]
user_id not in [user.id for user in users]
and user_id not in users_to_fetch
):
users_to_fetch.append(user_id)
@@ -217,7 +208,7 @@ class Client:
Raises:
FBchatException: If request failed
"""
data = {"viewer": self._uid}
data = {"viewer": self._session.user_id}
j = self._payload_post("/chat/user_info_all", data)
users = []
@@ -840,7 +831,7 @@ class Client:
elif i["node"].get("__typename") == "MessageVideo":
yield VideoAttachment._from_list(i)
else:
yield Attachment(uid=i["node"].get("legacy_attachment_id"))
yield Attachment(id=i["node"].get("legacy_attachment_id"))
del j[thread_id]["message_shared_media"]["edges"][0]
"""
@@ -876,7 +867,7 @@ class Client:
Raises:
FBchatException: If request failed
"""
thread = thread_type._to_class()(uid=thread_id)
thread = thread_type._to_class()(id=thread_id)
data = thread._to_send_data()
data.update(message._to_send_data())
return self._do_send_request(data)
@@ -895,7 +886,7 @@ class Client:
Raises:
FBchatException: If request failed
"""
thread = thread_type._to_class()(uid=thread_id)
thread = thread_type._to_class()(id=thread_id)
data = thread._to_send_data()
data["action_type"] = "ma-type:user-generated-message"
data["lightweight_action_attachment[lwa_state]"] = (
@@ -968,7 +959,7 @@ class Client:
def _send_location(
self, location, current=True, message=None, thread_id=None, thread_type=None
):
thread = thread_type._to_class()(uid=thread_id)
thread = thread_type._to_class()(id=thread_id)
data = thread._to_send_data()
if message is not None:
data.update(message._to_send_data())
@@ -1036,7 +1027,7 @@ class Client:
`files` should be a list of tuples, with a file's ID and mimetype.
"""
thread = thread_type._to_class()(uid=thread_id)
thread = thread_type._to_class()(id=thread_id)
data = thread._to_send_data()
data.update(self._old_message(message)._to_send_data())
data["action_type"] = "ma-type:user-generated-message"
@@ -1182,7 +1173,7 @@ class Client:
if len(user_ids) < 2:
raise ValueError("Error when creating group: Not enough participants")
for i, user_id in enumerate(user_ids + [self._uid]):
for i, user_id in enumerate(user_ids + [self._session.user_id]):
data["specific_to_list[{}]".format(i)] = "fbid:{}".format(user_id)
message_id, thread_id = self._do_send_request(data, get_thread_id=True)
@@ -1202,7 +1193,7 @@ class Client:
Raises:
FBchatException: If request failed
"""
data = Group(uid=thread_id)._to_send_data()
data = Group(id=thread_id)._to_send_data()
data["action_type"] = "ma-type:log-message"
data["log_message_type"] = "log:subscribe"
@@ -1210,7 +1201,7 @@ class Client:
user_ids = _util.require_list(user_ids)
for i, user_id in enumerate(user_ids):
if user_id == self._uid:
if user_id == self._session.user_id:
raise ValueError(
"Error when adding users: Cannot add self to group thread"
)
@@ -1286,7 +1277,7 @@ class Client:
data = {
"client_mutation_id": "0",
"actor_id": self._uid,
"actor_id": self._session.user_id,
"thread_fbid": thread_id,
"user_ids": user_ids,
"response": "ACCEPT" if approve else "DENY",
@@ -1459,7 +1450,7 @@ class Client:
data = {
"action": "ADD_REACTION" if reaction else "REMOVE_REACTION",
"client_mutation_id": "1",
"actor_id": self._uid,
"actor_id": self._session.user_id,
"message_id": str(message_id),
"reaction": reaction.value if reaction else None,
}
@@ -1504,7 +1495,7 @@ class Client:
FBchatException: If request failed
"""
data = {
"event_reminder_id": plan.uid,
"event_reminder_id": plan.id,
"delete": "false",
"date": _util.datetime_to_seconds(new_plan.time),
"location_name": new_plan.location or "",
@@ -1523,7 +1514,7 @@ class Client:
Raises:
FBchatException: If request failed
"""
data = {"event_reminder_id": plan.uid, "delete": "true", "acontext": ACONTEXT}
data = {"event_reminder_id": plan.id, "delete": "true", "acontext": ACONTEXT}
j = self._payload_post("/ajax/eventreminder/submit", data)
def change_plan_participation(self, plan, take_part=True):
@@ -1537,7 +1528,7 @@ class Client:
FBchatException: If request failed
"""
data = {
"event_reminder_id": plan.uid,
"event_reminder_id": plan.id,
"guest_state": "GOING" if take_part else "DECLINED",
"acontext": ACONTEXT,
}
@@ -1916,14 +1907,14 @@ class Client:
def _ping(self):
data = {
"seq": self._seq,
"channel": "p_" + self._uid,
"channel": "p_" + self._session.user_id,
"clientid": self._session._client_id,
"partition": -2,
"cap": 0,
"uid": self._uid,
"uid": self._session.user_id,
"sticky_token": self._sticky,
"sticky_pool": self._pool,
"viewer_uid": self._uid,
"viewer_uid": self._session.user_id,
"state": "active",
}
j = self._get(
@@ -2464,7 +2455,7 @@ class Client:
replied_to = Message._from_reply(i["repliedToMessage"])
message = Message._from_reply(i["message"], replied_to)
self.on_message(
mid=message.uid,
mid=message.id,
author_id=message.author,
message_object=message,
thread_id=thread_id,
@@ -2540,7 +2531,7 @@ class Client:
thread_id = str(thread_id)
else:
thread_type = ThreadType.USER
if author_id == self._uid:
if author_id == self._session.user_id:
thread_id = m.get("to")
else:
thread_id = author_id

View File

@@ -24,7 +24,7 @@ class FileAttachment(Attachment):
size=size,
name=data.get("filename"),
is_malicious=data.get("is_malicious"),
uid=data.get("message_file_fbid"),
id=data.get("message_file_fbid"),
)
@@ -86,7 +86,7 @@ class ImageAttachment(Attachment):
height=data.get("original_dimensions", {}).get("height"),
is_animated=data["__typename"] == "MessageAnimatedImage",
previews={p for p in previews if p},
uid=data.get("legacy_attachment_id"),
id=data.get("legacy_attachment_id"),
)
@classmethod
@@ -103,7 +103,7 @@ class ImageAttachment(Attachment):
width=data["original_dimensions"].get("x"),
height=data["original_dimensions"].get("y"),
previews={p for p in previews if p},
uid=data["legacy_attachment_id"],
id=data["legacy_attachment_id"],
)
@@ -139,7 +139,7 @@ class VideoAttachment(Attachment):
duration=_util.millis_to_timedelta(data.get("playable_duration_in_ms")),
preview_url=data.get("playable_url"),
previews={p for p in previews if p},
uid=data.get("legacy_attachment_id"),
id=data.get("legacy_attachment_id"),
)
@classmethod
@@ -151,7 +151,7 @@ class VideoAttachment(Attachment):
duration=_util.millis_to_timedelta(media.get("playable_duration_in_ms")),
preview_url=media.get("playable_url"),
previews={image} if image else {},
uid=data["target"].get("video_id"),
id=data["target"].get("video_id"),
)
@classmethod
@@ -167,7 +167,7 @@ class VideoAttachment(Attachment):
width=data["original_dimensions"].get("x"),
height=data["original_dimensions"].get("y"),
previews=previews,
uid=data["legacy_attachment_id"],
id=data["legacy_attachment_id"],
)
@@ -182,7 +182,7 @@ def graphql_to_attachment(data, size=None):
elif _type == "MessageFile":
return FileAttachment._from_graphql(data, size=size)
return Attachment(uid=data.get("legacy_attachment_id"))
return Attachment(id=data.get("legacy_attachment_id"))
def graphql_to_subattachment(data):

View File

@@ -10,6 +10,16 @@ class Group(Thread):
type = ThreadType.GROUP
#: The group's picture
photo = attr.ib(None)
#: The name of the group
name = attr.ib(None)
#: Datetime when the group was last active / when the last message was sent
last_active = attr.ib(None)
#: Number of messages in the group
message_count = attr.ib(None)
#: Set `Plan`
plan = attr.ib(None)
#: Unique list (set) of the group thread's participant user IDs
participants = attr.ib(factory=set)
#: A dictionary, containing user nicknames mapped to their IDs
@@ -42,7 +52,7 @@ class Group(Thread):
plan = _plan.Plan._from_graphql(data["event_reminders"]["nodes"][0])
return cls(
uid=data["thread_key"]["thread_fbid"],
id=data["thread_key"]["thread_fbid"],
participants=set(
[
node["messaging_actor"]["id"]
@@ -71,4 +81,4 @@ class Group(Thread):
)
def _to_send_data(self):
return {"thread_fbid": self.uid}
return {"thread_fbid": self.id}

View File

@@ -33,7 +33,7 @@ class LocationAttachment(Attachment):
latitude, longitude = None, None
return cls(
uid=int(data["deduplication_key"]),
id=int(data["deduplication_key"]),
latitude=latitude,
longitude=longitude,
image=Image._from_uri_or_none(data["media"].get("image"))
@@ -58,7 +58,7 @@ class LiveLocationAttachment(LocationAttachment):
@classmethod
def _from_pull(cls, data):
return cls(
uid=data["id"],
id=data["id"],
latitude=data["coordinate"]["latitude"] / (10 ** 8)
if not data.get("stopReason")
else None,
@@ -80,7 +80,7 @@ class LiveLocationAttachment(LocationAttachment):
image = Image._from_uri(media["image"])
return cls(
uid=int(target["live_location_id"]),
id=int(target["live_location_id"]),
latitude=target["coordinate"]["latitude"]
if target.get("coordinate")
else None,

View File

@@ -85,7 +85,7 @@ class Message:
#: A `EmojiSize`. Size of a sent emoji
emoji_size = attr.ib(None)
#: The message ID
uid = attr.ib(None)
id = attr.ib(None)
#: ID of the sender
author = attr.ib(None)
#: Datetime of when the message was sent
@@ -186,7 +186,7 @@ class Message:
data["sticker_id"] = self.emoji_size.value
if self.sticker:
data["sticker_id"] = self.sticker.uid
data["sticker_id"] = self.sticker.id
if self.quick_replies:
xmd = {"quick_replies": []}
@@ -255,7 +255,7 @@ class Message:
Mention._from_range(m) for m in data["message"].get("ranges") or ()
],
emoji_size=EmojiSize._from_tags(tags),
uid=str(data["message_id"]),
id=str(data["message_id"]),
author=str(data["message_sender"]["id"]),
created_at=created_at,
is_read=not data["unread"] if data.get("unread") is not None else None,
@@ -272,7 +272,7 @@ class Message:
attachments=attachments,
quick_replies=cls._parse_quick_replies(data.get("platform_xmd_encoded")),
unsent=unsent,
reply_to_id=replied_to.uid if replied_to else None,
reply_to_id=replied_to.id if replied_to else None,
replied_to=replied_to,
forwarded=cls._get_forwarded_from_tags(tags),
)
@@ -311,14 +311,14 @@ class Message:
for m in _util.parse_json(data.get("data", {}).get("prng", "[]"))
],
emoji_size=EmojiSize._from_tags(tags),
uid=metadata.get("messageId"),
id=metadata.get("messageId"),
author=str(metadata.get("actorFbId")),
created_at=_util.millis_to_datetime(metadata.get("timestamp")),
sticker=sticker,
attachments=attachments,
quick_replies=cls._parse_quick_replies(data.get("platform_xmd_encoded")),
unsent=unsent,
reply_to_id=replied_to.uid if replied_to else None,
reply_to_id=replied_to.id if replied_to else None,
replied_to=replied_to,
forwarded=cls._get_forwarded_from_tags(tags),
)
@@ -374,7 +374,7 @@ class Message:
text=data.get("body"),
mentions=mentions,
emoji_size=EmojiSize._from_tags(tags),
uid=mid,
id=mid,
author=author,
created_at=created_at,
sticker=sticker,
@@ -391,7 +391,7 @@ def graphql_to_extensible_attachment(data):
target = story.get("target")
if not target:
return _attachment.UnsentMessage(uid=data.get("legacy_attachment_id"))
return _attachment.UnsentMessage(id=data.get("legacy_attachment_id"))
_type = target["__typename"]
if _type == "MessageLocation":

View File

@@ -10,6 +10,16 @@ class Page(Thread):
type = ThreadType.PAGE
#: The page's picture
photo = attr.ib(None)
#: The name of the page
name = attr.ib(None)
#: Datetime when the thread was last active / when the last message was sent
last_active = attr.ib(None)
#: Number of messages in the thread
message_count = attr.ib(None)
#: Set `Plan`
plan = attr.ib(None)
#: The page's custom URL
url = attr.ib(None)
#: The name of the page's location city
@@ -32,7 +42,7 @@ class Page(Thread):
plan = _plan.Plan._from_graphql(data["event_reminders"]["nodes"][0])
return cls(
uid=data["id"],
id=data["id"],
url=data.get("url"),
city=data.get("city").get("name"),
category=data.get("category_type"),

View File

@@ -19,7 +19,7 @@ class Plan:
#: Plan title
title = attr.ib()
#: ID of the plan
uid = attr.ib(None)
id = attr.ib(None)
#: Plan location name
location = attr.ib(None, converter=lambda x: x or "")
#: Plan location ID
@@ -59,7 +59,7 @@ class Plan:
@classmethod
def _from_pull(cls, data):
return cls(
uid=data.get("event_id"),
id=data.get("event_id"),
time=_util.seconds_to_datetime(int(data.get("event_time"))),
title=data.get("event_title"),
location=data.get("event_location_name"),
@@ -74,7 +74,7 @@ class Plan:
@classmethod
def _from_fetch(cls, data):
return cls(
uid=data.get("oid"),
id=data.get("oid"),
time=_util.seconds_to_datetime(data.get("event_time")),
title=data.get("title"),
location=data.get("location_name"),
@@ -86,7 +86,7 @@ class Plan:
@classmethod
def _from_graphql(cls, data):
return cls(
uid=data.get("id"),
id=data.get("id"),
time=_util.seconds_to_datetime(data.get("time")),
title=data.get("event_title"),
location=data.get("location_name"),

View File

@@ -13,12 +13,12 @@ class Poll:
#: Options count
options_count = attr.ib(None)
#: ID of the poll
uid = attr.ib(None)
id = attr.ib(None)
@classmethod
def _from_graphql(cls, data):
return cls(
uid=int(data["id"]),
id=int(data["id"]),
title=data.get("title") if data.get("title") else data.get("text"),
options=[PollOption._from_graphql(m) for m in data.get("options")],
options_count=data.get("total_count"),
@@ -38,7 +38,7 @@ class PollOption:
#: Votes count
votes_count = attr.ib(None)
#: ID of the poll option
uid = attr.ib(None)
id = attr.ib(None)
@classmethod
def _from_graphql(cls, data):
@@ -49,7 +49,7 @@ class PollOption:
else:
vote = data["viewer_has_voted"] == "true"
return cls(
uid=int(data["id"]),
id=int(data["id"]),
text=data.get("text"),
vote=vote,
voters=(

View File

@@ -35,7 +35,7 @@ class Sticker(Attachment):
return None
return cls(
uid=data["id"],
id=data["id"],
pack=data["pack"].get("id") if data.get("pack") else None,
is_animated=bool(data.get("sprite_image")),
medium_sprite_image=data["sprite_image"].get("uri")

View File

@@ -71,20 +71,10 @@ class ThreadColor(Enum):
class Thread:
"""Represents a Facebook thread."""
#: The unique identifier of the thread. Can be used a ``thread_id``. See :ref:`intro_threads` for more info
uid = attr.ib(converter=str)
#: The unique identifier of the thread.
id = attr.ib(converter=str)
#: Specifies the type of thread. Can be used a ``thread_type``. See :ref:`intro_threads` for more info
type = None
#: The thread's picture
photo = attr.ib(None)
#: The name of the thread
name = attr.ib(None)
#: Datetime when the thread was last active / when the last message was sent
last_active = attr.ib(None)
#: Number of messages in the thread
message_count = attr.ib(None)
#: Set `Plan`
plan = attr.ib(None)
@staticmethod
def _parse_customization_info(data):
@@ -105,15 +95,15 @@ class Thread:
for k in info.get("participant_customizations", []):
rtn["nicknames"][k["participant_id"]] = k.get("nickname")
elif info.get("participant_customizations"):
uid = data.get("thread_key", {}).get("other_user_id") or data.get("id")
user_id = data.get("thread_key", {}).get("other_user_id") or data.get("id")
pc = info["participant_customizations"]
if len(pc) > 0:
if pc[0].get("participant_id") == uid:
if pc[0].get("participant_id") == user_id:
rtn["nickname"] = pc[0].get("nickname")
else:
rtn["own_nickname"] = pc[0].get("nickname")
if len(pc) > 1:
if pc[1].get("participant_id") == uid:
if pc[1].get("participant_id") == user_id:
rtn["nickname"] = pc[1].get("nickname")
else:
rtn["own_nickname"] = pc[1].get("nickname")
@@ -121,4 +111,4 @@ class Thread:
def _to_send_data(self):
# TODO: Only implement this in subclasses
return {"other_user_fbid": self.uid}
return {"other_user_fbid": self.id}

View File

@@ -47,6 +47,16 @@ class User(Thread):
type = ThreadType.USER
#: The user's picture
photo = attr.ib(None)
#: The name of the user
name = attr.ib(None)
#: Datetime when the thread was last active / when the last message was sent
last_active = attr.ib(None)
#: Number of messages in the thread
message_count = attr.ib(None)
#: Set `Plan`
plan = attr.ib(None)
#: The profile URL
url = attr.ib(None)
#: The users first name
@@ -78,7 +88,7 @@ class User(Thread):
plan = _plan.Plan._from_graphql(data["event_reminders"]["nodes"][0])
return cls(
uid=data["id"],
id=data["id"],
url=data.get("url"),
first_name=data.get("first_name"),
last_name=data.get("last_name"),
@@ -123,7 +133,7 @@ class User(Thread):
plan = _plan.Plan._from_graphql(data["event_reminders"]["nodes"][0])
return cls(
uid=user["id"],
id=user["id"],
url=user.get("url"),
name=user.get("name"),
first_name=first_name,
@@ -144,7 +154,7 @@ class User(Thread):
@classmethod
def _from_all_fetch(cls, data):
return cls(
uid=data["id"],
id=data["id"],
first_name=data.get("firstName"),
url=data.get("uri"),
photo=Image(url=data.get("thumbSrc")),