Skip to content
This repository has been archived by the owner on Aug 12, 2024. It is now read-only.

Commit

Permalink
Merge pull request #68 from quintindunn/development
Browse files Browse the repository at this point in the history
Merge development into main
  • Loading branch information
quintindunn authored Nov 23, 2023
2 parents dc6b5f6 + 94ef3a4 commit da091a4
Show file tree
Hide file tree
Showing 20 changed files with 446 additions and 46 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ __pycache__
lapsepy.egg-info
dist
build
examples/get_friends_feed/out
examples/get_friends_feed/out
examples/darkroom_query/out
12 changes: 12 additions & 0 deletions examples/block_user/block_user_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os

from lapsepy.lapse import Lapse

if __name__ == '__main__':
lapse = Lapse(os.getenv("REFRESH_TOKEN"))

username_to_block = input("Username to block: ")

user = lapse.get_profile_by_username(username_to_block)

lapse.block_profile(user)
12 changes: 12 additions & 0 deletions examples/block_user/block_user_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os

from lapsepy.lapse import Lapse

if __name__ == '__main__':
lapse = Lapse(os.getenv("REFRESH_TOKEN"))

username_to_block = input("Username to block: ")

user = lapse.get_profile_by_username(username_to_block)

user.block(lapse)
18 changes: 18 additions & 0 deletions examples/darkroom_query/darkroom_query_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import os

from lapsepy.lapse import Lapse

if __name__ == '__main__':
lapse = Lapse(os.getenv("REFRESH_TOKEN"))

darkroom_media = lapse.query_darkroom()

if not os.path.isdir("./out"):
os.mkdir("./out")

for content in darkroom_media:
# Load the image
im = content.load()

# Save the image
im.save(f"./out/{content.media_id}.jpeg", format="jpeg")
12 changes: 12 additions & 0 deletions examples/get_album_by_id/get_album_by_id_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os
from lapsepy.lapse import Lapse

if __name__ == '__main__':
lapse = Lapse(refresh_token=os.getenv("REFRESH_TOKEN"))

album_id = input("Album ID: ")

album = lapse.get_album_by_id(album_id, last=10)

for media in album.media:
im = media.load()
12 changes: 12 additions & 0 deletions examples/unblock_user/unblock_user_01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os

from lapsepy.lapse import Lapse

if __name__ == '__main__':
lapse = Lapse(os.getenv("REFRESH_TOKEN"))

username_to_block = input("Username to unblock: ")

user = lapse.get_profile_by_username(username_to_block)

lapse.unblock_profile(user)
12 changes: 12 additions & 0 deletions examples/unblock_user/unblock_user_02.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os

from lapsepy.lapse import Lapse

if __name__ == '__main__':
lapse = Lapse(os.getenv("REFRESH_TOKEN"))

username_to_block = input("Username to unblock: ")

user = lapse.get_profile_by_username(username_to_block)

user.unblock(ctx=lapse)
2 changes: 1 addition & 1 deletion lapsepy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Date: 10/22/23
"""

__version__ = '1.0.3'
__version__ = '1.1.0'

from .journal import Journal
from .auth.refresher import refresh
Expand Down
1 change: 1 addition & 0 deletions lapsepy/journal/factory/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
from .media_factory import ImageUploadURLGQL, CreateMediaGQL, SendInstantsGQL
from .profile_factory import SaveDisplayNameGQL, SaveDOBGQL, SaveUsernameGQL, SaveBioGQL, SaveEmojisGQL
from .friends_factory import FriendsFeedItemsGQL
from .album_factory import AlbumMediaGQL
33 changes: 33 additions & 0 deletions lapsepy/journal/factory/album_factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
Author: Quintin Dunn
Date: 11/23/23
"""
from lapsepy.journal.factory.factory import BaseGQL


class AlbumMediaGQL(BaseGQL):
def __init__(self, album_id: str, last: int):
super().__init__("AlbumMediaGraphQLQuery",
"query AlbumMediaGraphQLQuery($id: ID!, $first: Int, $after: String, $last: Int, $before: "
"String) { album(id: $id) { __typename id media(first: $first, after: $after, last: $last, "
"before: $before) { __typename totalCount edges { __typename cursor node { __typename "
"...AlbumMediaDetails } } pageInfo { __typename startCursor endCursor hasNextPage "
"hasPreviousPage } } } }\nfragment AlbumMediaDetails on AlbumMedia { __typename addedAt { "
"__typename isoString } media { __typename ...CoreMediaFragment } }\nfragment "
"CoreMediaFragment on Media { __typename id takenAt { __typename isoString } takenBy { "
"__typename ...CoreProfileFragment } deletedAt { __typename isoString } }\nfragment "
"CoreProfileFragment on Profile { __typename id displayName profilePhotoName username "
"friendStatus isBlocked blockedMe hashedPhoneNumber joinedAt { __typename isoString } }")

self.album_id = album_id
self.last = last

self.variables = {}

self._render_variables()

def _render_variables(self):
self.variables = {
"id": self.album_id,
"last": self.last
}
34 changes: 34 additions & 0 deletions lapsepy/journal/factory/profile_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,37 @@ def _render_variables(self):
"songTitle": self.song_title,
"songUrl": self.song_url
}


class BlockProfileGQL(BaseGQL):
def __init__(self, user_id: str):
super().__init__("BlockProfileGraphQLMutation",
"mutation BlockProfileGraphQLMutation($input: BlockProfileInput!) "
"{ blockProfile(input: $input) { __typename success } }")
self.user_id = user_id

self.variables = {}

self._render_variables()

def _render_variables(self):
self.variables['input'] = {
"id": self.user_id
}


class UnblockProfileGQL(BaseGQL):
def __init__(self, user_id: str):
super().__init__("UnblockProfileGraphQLMutation",
"mutation UnblockProfileGraphQLMutation($input: UnblockProfileInput!) "
"{ unblockProfile(input: $input) { __typename success } }")
self.user_id = user_id

self.variables = {}

self._render_variables()

def _render_variables(self):
self.variables['input'] = {
"id": self.user_id
}
105 changes: 98 additions & 7 deletions lapsepy/journal/journal.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import io
import uuid

from .common.exceptions import sync_journal_exception_router, SyncJournalException
from .common.exceptions import sync_journal_exception_router, SyncJournalException, AuthTokenExpired

from uuid import uuid4
from datetime import datetime
Expand All @@ -22,10 +22,12 @@
DarkroomGQL

from lapsepy.journal.factory.profile_factory import SaveBioGQL, SaveDisplayNameGQL, SaveUsernameGQL, SaveEmojisGQL, \
SaveDOBGQL, CurrentUserGQL, SaveMusicGQL
SaveDOBGQL, CurrentUserGQL, SaveMusicGQL, BlockProfileGQL, UnblockProfileGQL

from lapsepy.journal.factory.album_factory import AlbumMediaGQL

from .structures import Snap, Profile, ProfileMusic, FriendsFeed, FriendNode, DarkRoomMedia, ReviewMediaPartition, \
SearchUser
SearchUser, Album, AlbumMedia

import logging

Expand All @@ -42,11 +44,12 @@ def parse_iso_time(iso_str: str) -> datetime:


class Journal:
def __init__(self, authorization: str):
def __init__(self, authorization: str, refresher):
self.request_url = "https://sync-service.production.journal-api.lapse.app/graphql"
self.base_headers = {
"authorization": authorization
}
self.refresher = refresher

def _sync_journal_call(self, query: dict) -> dict:
"""
Expand All @@ -56,8 +59,12 @@ def _sync_journal_call(self, query: dict) -> dict:
"""

logger.debug(f"Making request to {self.request_url}")

request = requests.post(self.request_url, headers=self.base_headers, json=query)
try:
request = requests.post(self.request_url, headers=self.base_headers, json=query)
except AuthTokenExpired:
self.refresher()
logger.debug("Auth token expired, retrying.")
return self._sync_journal_call(query=query)
try:
request.raise_for_status()
except requests.exceptions.HTTPError:
Expand Down Expand Up @@ -360,7 +367,7 @@ def generate_profile_object(profile_data: dict) -> Profile:
else:
profile_music = None

return Profile(
usr_profile = Profile(
bio=profile_data.get('bio'),
blocked_me=profile_data.get('blockedMe'),
display_name=profile_data.get('displayName'),
Expand All @@ -376,6 +383,38 @@ def generate_profile_object(profile_data: dict) -> Profile:
profile_music=profile_music
)

album_data = profile_data.get("albums", {}).get("edges", {})

albums = []

for album_edge in album_data:
album_node = album_edge['node']

album_media = []
for media_edge in album_node.get("media", {}).get("edges", {}):
node = media_edge.get("node")
# added_at: datetime, media_id: str, taken_at: datetime, capturer_id: str
album_media.append(AlbumMedia(
added_at=parse_iso_time(node.get("addedAt", {}).get("isoString")),
taken_at=parse_iso_time(node.get("addedAt", {}).get("isoString")),
media_id=node.get("media", {}).get("id"),
capturer_id=usr_profile.user_id
))

albums.append(Album(
album_id=album_node.get("id"),
media=album_media,
album_name=album_node.get("name"),
visibility=album_node.get("visibility"),
created_at=parse_iso_time(album_node.get("createdAt", {}).get("isoString")),
updated_at=parse_iso_time(album_node.get("updatedAt", {}).get("isoString")),
owner=usr_profile
))

usr_profile.albums = albums

return usr_profile

profile = generate_profile_object(pd)

# Generate friend objects
Expand Down Expand Up @@ -555,3 +594,55 @@ def search_for_user(self, term: str, first: int = 10) -> list[SearchUser]:
users.append(search_user)

return users

def block_user(self, user_id: str):
"""
Send a user blocking API call
:param user_id: ID of the user to block
:return:
"""
query = BlockProfileGQL(user_id=user_id).to_dict()
response = self._sync_journal_call(query)

if not response.get("data", {}).get("blockProfile", {}).get("success"):
raise SyncJournalException(f"Error blocking user {user_id}.")

def unblock_user(self, user_id: str):
"""
Send a user unblocking API call
:param user_id: ID of the user to unblock
:return:
"""
query = UnblockProfileGQL(user_id=user_id).to_dict()
response = self._sync_journal_call(query)

if not response.get("data", {}).get("unblockProfile", {}).get("success"):
raise SyncJournalException(f"Error unblocking user {user_id}.")

def get_album_by_id(self, album_id: str, last: int):
"""
Gets an album by its ID.
:param album_id: ID of the album
:param last: How many items to query from the album.
:return:
"""
query = AlbumMediaGQL(album_id=album_id, last=last).to_dict()

response = self._sync_journal_call(query)

if response.get("errors"):
raise SyncJournalException(f"Error getting album {album_id}")

album_data = response.get("data", {}).get("album", {})

media = []

for edge in album_data.get("media", {}).get("edges", {}):
node = edge['node']

album_media = AlbumMedia.from_dict(album_data=node)
media.append(album_media)

album = Album(album_id=album_id, media=media)

return album
1 change: 1 addition & 0 deletions lapsepy/journal/structures/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
from .snap import Snap, DarkRoomMedia, ReviewMediaPartition
from .friendsfeed import FriendsFeed, FriendNode
from .searches import SearchUser
from .album import Album, AlbumMedia
Loading

0 comments on commit da091a4

Please sign in to comment.