Skip to content

Commit

Permalink
add Instagram.id_to_shortcode. for snarfed/bridgy#603
Browse files Browse the repository at this point in the history
  • Loading branch information
snarfed committed Mar 30, 2016
1 parent 8868c38 commit 6f312e3
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
26 changes: 25 additions & 1 deletion granary/instagram.py
Expand Up @@ -9,14 +9,15 @@

__author__ = ['Ryan Barrett <granary@ryanb.org>']

import xml.sax.saxutils
import datetime
import json
import logging
import operator
import string
import urllib
import urllib2
import urlparse
import xml.sax.saxutils

import appengine_config
from oauth_dropins.webutil import util
Expand All @@ -39,6 +40,8 @@

HTML_MEDIA = 'https://www.instagram.com/p/%s/'

# URL-safe base64 encoding. used in Instagram.id_to_shortcode()
BASE64 = string.ascii_uppercase + string.ascii_lowercase + string.digits + '-_'

class Instagram(source.Source):
"""Implements the ActivityStreams API for Instagram."""
Expand Down Expand Up @@ -588,6 +591,27 @@ def base_object(self, obj):

return base_obj

@staticmethod
def id_to_shortcode(id):
"""Converts a media id to the shortcode used in its instagram.com URL.
Based on http://carrot.is/coding/instagram-ids , which determined that
shortcodes are just URL-safe base64 encoded ids.
"""
if not id:
return None

if isinstance(id, basestring):
id = int(id.split('_')[0])

A = ord('A')
chars = []
while id > 0:
id, rem = divmod(id, 64)
chars.append(BASE64[rem])

return ''.join(reversed(chars))

def html_to_activities(self, html):
"""Converts Instagram HTML to ActivityStreams activities.
Expand Down
11 changes: 11 additions & 0 deletions granary/test/test_instagram.py
Expand Up @@ -1215,3 +1215,14 @@ def test_html_to_activities_missing_video_url(self):
del expected[1]['object']['stream']
del expected[1]['object']['attachments'][0]['stream'][0]['url']
self.assert_equals(expected, activities)

def test_id_to_shortcode(self):
for shortcode, id in (
(None, None),
(None, ''),
('BDJ7Nr5Nxpa', 1209758400153852506),
('BDJ7Nr5Nxpa', '1209758400153852506'),
('BDJ7Nr5Nxpa', '1209758400153852506'),
('BDJ7Nr5Nxpa', '1209758400153852506_1103525'),
):
self.assertEquals(shortcode, self.instagram.id_to_shortcode(id))

0 comments on commit 6f312e3

Please sign in to comment.