Skip to content

Commit

Permalink
Support GEO location when publish media [#6] Added Location.location_…
Browse files Browse the repository at this point in the history
…info and extract_location
  • Loading branch information
adw0rd committed Nov 2, 2020
1 parent a4a4e67 commit 5ee41ab
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 41 deletions.
49 changes: 24 additions & 25 deletions instagrapi/extractors.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,6 @@ def extract_media_v1(data):
"""
user = data["user"]
location = data.get("location")
if location:
# {'pk': 262547125,
# 'name': 'NAME',
# 'address': 'ADDRESS',
# 'city': 'SANKT-PETERBURG',
# 'short_name': 'NAME',
# 'lng': 42.000000000001,
# 'lat': 42.000000000002,
# 'external_source': 'facebook_places',
# 'facebook_places_id': 232571358171010}
location = {
"pk": int(location.get("pk")),
"name": location.get("name"),
"lat": location.get("lat"),
"lng": location.get("lng"),
}
video_url = ""
if "video_versions" in data:
# Select Best Quality by Resolutiuon
Expand All @@ -45,7 +29,7 @@ def extract_media_v1(data):
"product_type": product_type,
"code": data["code"],
"thumbnail_url": thumbnail_url,
"location": location or {},
"location": extract_location(location) if location else {},
"user": extract_user_short(user),
"comment_count": int(data.get("comment_count") or 0),
# the media just published has no like_count
Expand Down Expand Up @@ -83,13 +67,6 @@ def extract_media_gql(data):
else:
user["pk"] = user.pop("id")
location = data.get("location")
if location:
location = {
"pk": int(location.get("id")),
"name": location.get("name"),
"lat": location.get("lat"),
"lng": location.get("lng"),
}
media_type = {"GraphImage": 1, "GraphVideo": 2,
"GraphSidecar": 8}[data["__typename"]]
product_type = data.get("product_type", "")
Expand All @@ -113,7 +90,7 @@ def extract_media_gql(data):
data.get("display_resources", data.get('thumbnail_resources')),
key=lambda o: o["config_width"] * o["config_height"],
).pop()["src"],
"location": location or {},
"location": extract_location(location) if location else {},
"user": user,
"comment_count": json_value(data, "edge_media_to_comment", "count"),
"like_count": json_value(data, "edge_media_preview_like", "count"),
Expand Down Expand Up @@ -245,3 +222,25 @@ def extract_user_v1(data):
"external_url": data["external_url"],
"is_business": data["is_business"],
}


def extract_location(data):
"""Extract location from v1/gql
v1 example: {
'pk': 262547125,
'name': 'NAME',
'address': 'ADDRESS',
'city': 'SANKT-PETERBURG',
'short_name': 'NAME',
'lng': 42.000000000001,
'lat': 42.000000000002,
'external_source': 'facebook_places',
'facebook_places_id': 232571358171010
}
"""
return {
"pk": int(data.get("pk", data.get("id"))),
"name": data.get("name"),
"lat": data.get("lat"),
"lng": data.get("lng"),
}
13 changes: 13 additions & 0 deletions instagrapi/location.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import json

from .extractors import extract_location


class Location:

Expand Down Expand Up @@ -43,3 +45,14 @@ def location_build(self, location):
except IndexError:
pass
return json.dumps(location, separators=(",", ":"))

def location_info_a1(self, location_pk: int) -> dict:
"""Return additonal info for location by ?__a=1
"""
data = self.public_a1_request(f"/explore/locations/{location_pk}/")
return extract_location(data['location'])

def location_info(self, location_pk: int) -> dict:
"""Return additonal info for location
"""
return self.location_info_a1(location_pk)
12 changes: 9 additions & 3 deletions instagrapi/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,13 @@ def media_info_gql(self, media_pk: int) -> dict:
)
if not data.get("shortcode_media"):
raise MediaNotFound(media_pk=media_pk, **data)
return extract_media_gql(data["shortcode_media"])
media = extract_media_gql(data["shortcode_media"])
location = media.get('location')
if location:
location_pk = location.get('pk')
if not location.get('lat') and location_pk:
media['location'] = self.location_info(location_pk)
return media

def media_info_v1(self, media_pk: int) -> dict:
try:
Expand Down Expand Up @@ -128,7 +134,7 @@ def media_delete(self, media_id: str, media_type: str = '') -> bool:
self._medias_cache.pop(self.media_pk(media_id), None)
return result.get("did_delete")

def media_edit(self, media_id: str, caption: str, title: str = "", usertags: list = []) -> bool:
def media_edit(self, media_id: str, caption: str, title: str = "", usertags: list = [], location: dict = {}) -> bool:
"""Edit caption for media
Example: https://i.instagram.com/api/v1/media/2154602296692269830_1903424587/edit_media/
Expand Down Expand Up @@ -167,7 +173,7 @@ def media_edit(self, media_id: str, caption: str, title: str = "", usertags: lis
"caption_text": caption,
"container_module": "edit_media_info",
"feed_position": "0",
"location": "{}",
"location": self.location_build(location),
"usertags": json.dumps({"in": usertags}),
"is_carousel_bumped_post": "false",
}
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

setup(
name='instagrapi',
version='1.2.1',
version='1.2.2',
author='Mikhail Andreev',
author_email='[email protected]',
license='MIT',
Expand Down
23 changes: 11 additions & 12 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,13 @@ def test_media_comment(self):


class ClientCompareExtractTestCase(ClientPrivateTestCase):
def assertLocation(self, one, two):
for key, val in one.items():
gql = two[key]
if isinstance(val, float):
val, gql = round(val, 4), round(gql, 4)
self.assertEqual(val, gql)

def test_two_extract_media_photo(self):
# Photo with usertags
media_pk = 2154602296692269830
Expand All @@ -314,9 +321,7 @@ def test_two_extract_media_photo(self):
self.assertTrue(media_v1.pop("thumbnail_url").startswith("https://"))
self.assertTrue(media_gql.pop("thumbnail_url").startswith("https://"))
self.assertTrue(media_v1.pop("comment_count") <= media_gql.pop("comment_count"))
location_v1, location_gql = media_v1.pop('location'), media_gql.pop('location')
for key in ('name', 'pk'):
self.assertEqual(location_v1.get(key), location_gql.get(key))
self.assertLocation(media_v1.pop('location'), media_gql.pop('location'))
self.assertDictEqual(media_v1, media_gql)

def test_two_extract_media_video(self):
Expand All @@ -328,9 +333,7 @@ def test_two_extract_media_video(self):
self.assertTrue(media_v1.pop("video_url").startswith("https://"))
self.assertTrue(media_gql.pop("thumbnail_url").startswith("https://"))
self.assertTrue(media_gql.pop("video_url").startswith("https://"))
location_v1, location_gql = media_v1.pop('location'), media_gql.pop('location')
for key in ('name', 'pk'):
self.assertEqual(location_v1.get(key), location_gql.get(key))
self.assertLocation(media_v1.pop('location'), media_gql.pop('location'))
self.assertDictEqual(media_v1, media_gql)

def test_two_extract_media_album(self):
Expand All @@ -346,9 +349,7 @@ def test_two_extract_media_album(self):
self.assertTrue(res.pop("thumbnail_url").startswith("https://"))
if res['media_type'] == 2:
self.assertTrue(res.pop("video_url").startswith("https://"))
location_v1, location_gql = media_v1.pop('location'), media_gql.pop('location')
for key in ('name', 'pk'):
self.assertEqual(location_v1.get(key), location_gql.get(key))
self.assertLocation(media_v1.pop('location'), media_gql.pop('location'))
self.assertDictEqual(media_v1, media_gql)

def test_two_extract_media_igtv(self):
Expand All @@ -360,9 +361,7 @@ def test_two_extract_media_igtv(self):
self.assertTrue(media_v1.pop("video_url").startswith("https://"))
self.assertTrue(media_gql.pop("thumbnail_url").startswith("https://"))
self.assertTrue(media_gql.pop("video_url").startswith("https://"))
location_v1, location_gql = media_v1.pop('location'), media_gql.pop('location')
for key in ('name', 'pk'):
self.assertEqual(location_v1.get(key), location_gql.get(key))
self.assertLocation(media_v1.pop('location'), media_gql.pop('location'))
self.assertDictEqual(media_v1, media_gql)


Expand Down

0 comments on commit 5ee41ab

Please sign in to comment.