Friday, November 30, 2018

Google+ Migration - Part VI: Location, Location, Location!

<- Image Attachments

Before we focus on putting all the pieces together, here a small, optional excursion into how to make use of location information contained in G+ posts.

We should consider carefully if and how we want to include geo location information as there might be privacy and safety implications. For such locations, it can make sense to choose the point of a nearby landmark or add some random noise to the location coordinates.

Many of my public photo sharing post containing the location of near where the photos where taken. Diaspora* posts can contain a location tag as well, but it does not seem to be very informative and the diaspy API currently does not support adding post a post location.

Instead we can process the location information contained in the post takeout JSON files and transform it to extract some information which we can use to format the new posts.

In particular, we want to include a location link to the corresponding location on Openstreetmap as well as generate some additional hashtags from the location information, e.g. which country or city the post relates to.

Using the longitude & latitude coordinates from the location info, we can directly link to the corresponding location for example on Openstreetmap or other online mapping services.

"location": {
    "latitude": 40.7414688,
    "longitude": -74.0033873,
    "displayName": "111 8th Ave",
    "physicalAddress": "111 8th Ave, New York, NY 10011, USA"

In order to extract hierarchical location information like the country or the city of the location, we are calling the reverse-geocoding API of Openstreetmap with the coordinates to find the nearest recorded address of that point. To simply calling the web-api, we can use the geopy library (install for example with pip install geopy).

From various components of the address, we can generate location hashtags that help define the context of the post. The use of the additional pycountry module which contains a library of canonical country names by ISO-3166 country-codes is entirely optional but helps to create a more consistent label.

For the location record above, we can generate the following additional content snippets:

#US #UnitedStates #NYC

#!/usr/bin/env python

import codecs
import geopy.geocoders
import json
import pycountry
import sys

geocoder = geopy.geocoders.Nominatim(user_agent='gplus_migration', timeout=None)

def get_location_hashtags(loc):
  hashtags = []
  if 'latitude' in loc and 'longitude' in loc:
    addr = geocoder.reverse((loc['latitude'], loc['longitude'])).raw
    if 'address' in addr:
      addr = addr['address']
      cc = addr['country_code'].upper()
      hashtags.append(pycountry.countries.get(alpha_2=cc).name.replace(' ',''))
      for location in ['city', 'town', 'village']:
        if location in addr:
          hashtags.append(addr[location].replace(' ', ''))
  return hashtags

def get_location_link(loc):
  if 'latitude' in loc and 'longitude' in loc and 'displayName' in loc:
    map_url = ('' % (loc['latitude'], loc['longitude']))
    return '[%s](%s)' % (loc['displayName'], map_url)

sys.stdout = codecs.getwriter('utf8')(sys.stdout)

for filename in sys.stdin.readlines():
  filename = filename.strip()
  post = json.load(open(filename))  
  if 'location' in post:
    print(' '.join(('#' + tag for tag in get_location_hashtags(post['location']))))

Wednesday, November 28, 2018

Google+ Migration - Part V: Image Attachments

< - Part IV: Visibility Scope & Filtering

Google+ has always been rather good at dealing with photos - the photo functions were built on the foundation of Picasa and later spun out as Google Photos. Not surprising that the platform was popular with photographers and many posts contain photos.
In the takeout archive, photos or images/media file attachments to posts are rather challenging. In addition to the .json files containing each of the posts, the Takeout/Google+ Stream/Posts directory also includes two files for each image attached to a post. The basename is the originally uploaded filename, with a .jpg extension for the image file itself and a jpg.metadata.csv for for some additional information about the image.

If we originally attached an image cat.jpg to a post, there should now be a cat.jpg and cat.jpg.metadata.csv file in the post directory. However if over the years, we have been unimaginative in naming files and uploaded several cat.jpg images, there is now a name-clash that is resolved by the takeout archive by arbitrarily naming the files cat.jpg, cat(1).jpg, cat(2).jpg and so one.

The main challenge for reconstituting posts is to identify which image files is being references from which post.  The section of the JSON object which describes an image attachment looks like this example below. There is no explicit reference to the image filename in the archive nor does the metadata file contain the resourceName indicated here. There is a URL in the metadata file as well, but unfortunately it does not seem to match. The only heuristic left to try would be to take the last part of the URL path as an indication of the original filename and try to find a file with the same name. However this runs into the issue above with filename de-duplication where possibly the wrong photo would be linked to a post. For users with a combination of public and private post, such mixups could lead to very unintended consequences.

"media": {
      "url": "",
      "contentType": "image/*",
      "width": 900,
      "height": 1075,
      "resourceName": "media/CixBRjFRaXBPQ21aY2tlQ3h1OFVpamZJMDNpa0lqa1BsSmZ3b1ZNOWRvZlp2Qg\u003d\u003d"

It appears that at in this time, we are unable to reliably reconstruct the post to image file reference reliably from the contents of archive. The alternative is to download each of the URLs referenced in the post data from the Google static content server for as long as these resources are still available.

Fortunately with the given URLs this is rather simple to do in Python. We can process the JSON files once again, find all the image references and download the images to a local cache where they are stored with filenames derived from the (presumably) unique resource names. For further re-formatting of the posts, we can then refer to the downloaded images by their new unique names.

We can use the filter command from the previous blog-post to select which post we are interested in (again all public posts in this case) and pipe the output into this scrip to build up the image cache:

ls ~/Desktop/Takeout/Google+\ Stream/Posts/*.json | ./ --public --id communities/113390432655174294208 --id communities/103604153020461235235 --id communities/112164273001338979772 | ./ --image-dir=./images

#!/usr/bin/env python

import argparse
import codecs
import json
import os
import sys
import urllib
import urlparse
import sys

def get_image_name(resource_name):
  return resource_name.replace('media/', '', 1) + '.jpg'

def process_image(media, image_dir):
  url = media['url']
  id = media['resourceName']
  if media['contentType'] != 'image/*':
  if not url.startswith('http'): # patch for broken URLs...
    url = 'https:' + url
  target_name = os.path.join(image_dir, get_image_name(id))

  if os.path.exists(target_name):
    print('retrieving %s as %s' % (url, target_name))
    urllib.urlretrieve(url, target_name)

# --------------------
parser = argparse.ArgumentParser(description='Collect post images referenced from a set of posts')
parser.add_argument('--image-dir', dest='image_dir', action='store', required=True)
args = parser.parse_args()

if not os.path.exists(args.image_dir):

sys.stdout = codecs.getwriter('utf8')(sys.stdout)

for filename in sys.stdin.readlines():
  filename = filename.strip()
  post = json.load(open(filename))  
  if 'media' in post:
    process_image(post['media'], args.image_dir)
  elif 'album' in post:
    for image in post['album']['media']:
      process_image(image, args.image_dir)

Sunday, November 18, 2018

Google+ Migration - Part IV: Visibility Scope & Filtering

<- Part III: Content Transformation

Circles and with them the ability to share different content with different sets of people was one of the big differentiators of Google+ over other platforms at the time, which typically had a fixed sharing model and visibility scope.

Circles were based on the observation that most people in real life interact with several "social circles" and often would not want these circles to mix. The idea of Google+ was that it should be possible to manage all these different circles under a single online identity (which should also match the "real name" identity of our governments civil registry).

It turns out that while the observation of disjoint social circles was correct, most users prefer to use different platform and online identities to manage to make sure they don't inadvertently mix. Google+ tried hard to make sharing scopes obvious and unsurprising, but the model remained complex, hard to understand and accidents were only ever one or two mouse-clicks away.

Nevertheless, many takeout archives may contain posts that were intended for very different audiences and have different visibility that may still matter deeply to users. We are presenting here a tool that could help to analyze the sharing scopes that are present in a takeout archive and partition its content by selecting any subset of them.

The access control section (ACL) of each post has grown even more complex over time with the introduction of communities and collections. In particular there seem to be following distinct ways of defining the visibility of a post (some of which can be combined):
  • Public
  • Shared with all my circles
  • Shared with my extended circles (user in all my circles and their circles, presumably)
  • Shared with a particular circle
  • Shared with a particular user
  • Part of a collection (private or public)
  • Part of a community (closed or public)
Since my archive does not contain all these combinations, the code for processing the JSON definition of the post sharing and visibility scope is based on the following inferred schema definition. Please report if you encounter any exception from this structure.

After saving the following Python code in a file, e.g. and making it executable (chmod +x we can start by analyzing the existing visibility scopes that exist in a list of post archive files:

$ ls ~/Desktop/Takeout/Google+\ Stream/Posts/*.json | ./
1249 - PUBLIC 
227 - CIRCLE (Personal): circles/117832126248716550930-4eaf56378h22b473 
20 - COMMUNITY (Alte St├Ądte / Old Towns): communities/103604153020461235235 
9 - COMMUNITY (Raspberry Pi): communities/113390432655174294208 
1 - COMMUNITY (Google+ Mass Migration): communities/112164273001338979772 
1 - COMMUNITY (Free Open Source Software in Schools): communities/100565566447202592471

For my own purposes, I would consider all public posts as well as posts to public communities as essentially public and any posts that were restricted to any circles as essentially private. By carefully copying the community IDs from the output above, we can create the following filter condition to selection only the filenames of these essentially public posts from the archive:

ls ~/Desktop/Takeout/Google+\ Stream/Posts/*.json | ./ --public --id communities/113390432655174294208 --id communities/103604153020461235235 --id communities/112164273001338979772

We can then use the resulting list of filenames to only process post which are meant to be public. In a similar way, we could also extract posts that were shared with a particular circle or community, e.g. to assist in building a joint post archive for a particular community across its members.

#!/usr/bin/env python

import argparse
import codecs
import json
import optparse
import sys

class Visibility:

def parse_acl(acl):
  result = []

  # Post is public or has a visiblility defined by circles and/or users.
  if 'visibleToStandardAcl' in acl:
    if 'circles' in acl['visibleToStandardAcl']:
      for circle in acl['visibleToStandardAcl']['circles']:
        if circle['type'] == 'CIRCLE_TYPE_PUBLIC':
          result.append((Visibility.PUBLIC, None, None))
        elif circle['type'] == 'CIRCLE_TYPE_YOUR_CIRCLES':
          result.append((Visibility.CIRCLES, None, None))
        elif circle['type'] == 'CIRCLE_TYPE_EXTENDED_CIRCLES':
          result.append((Visibility.EXTENDED, None, None))
        elif circle['type'] == 'CIRCLE_TYPE_USER_CIRCLE':
          result.append((Visibility.CIRCLE, circle['resourceName'], circle.get('displayName', '')))
    if 'users' in acl['visibleToStandardAcl']:
      for user in acl['visibleToStandardAcl']['users']:
        result.append((Visibility.USER, user['resourceName'], user.get('displayName', '-')))

  # Post is part of a collection (could be public or private).
  if 'collectionAcl' in acl:
    collection = acl['collectionAcl']['collection']
    result.append((Visibility.COLLECTION, collection['resourceName'], collection.get('displayName', '-')))

  # Post is part of a community (could be public or closed).
  if 'communityAcl' in acl:
    community = acl['communityAcl']['community']
    result.append((Visibility.COMMUNITY, community['resourceName'], community.get('displayName', '-')))
    if 'users' in acl['communityAcl']:
      for user in acl['communityAcl']['users']:
        result.append((Visibility.USER, user['resourceName'], user.get('displayName', '-')))

  # Post is part of an event.
  if 'eventAcl' in acl:
    event = acl['eventAcl']['event']
    result.append((Visibility.EVENT, event['resourceName'], user.get('displayName', '-')))

  return result

parser = argparse.ArgumentParser(description='Filter G+ post JSON file by visibility')
parser.add_argument('--public', dest='scopes', action='append_const', const=Visibility.PUBLIC) 
parser.add_argument('--circles', dest='scopes',action='append_const', const=Visibility.CIRCLES)
parser.add_argument('--ext-circles', dest='scopes',action='append_const', const=Visibility.EXTENDED)
parser.add_argument('--id', dest='scopes',action='append')

args = parser.parse_args()
scopes = frozenset(args.scopes) if args.scopes != None else frozenset()

stats = {}
for filename in sys.stdin.readlines():
  filename = filename.strip()
  post = json.load(open(filename))  
  acls = parse_acl(post['postAcl'])
  for acl in acls:
    if len(scopes) == 0:
      stats[acl] = stats.get(acl, 0) + 1
      if acl[0] in (Visibility.PUBLIC, Visibility.CIRCLES, Visibility.EXTENDED) and acl[0] in scopes:
        print (filename)
      elif acl[1] in scopes:
        print (filename)
if len(scopes) == 0:
  sys.stdout = codecs.getwriter('utf8')(sys.stdout)
  for item in sorted(stats.items(), reverse=True, key=lambda x: x[1]):
    if item[0][0] in (Visibility.PUBLIC, Visibility.CIRCLES, Visibility.EXTENDED):
      print ('%d - %s' % (item[1], item[0][0]))
      print ('%d - %s (%s):\t %s' % (item[1], item[0][0], item[0][2], item[0][1]))

Sunday, November 11, 2018

Google+ Migration - Part III: Content Transformation

<- Part II: Understanding the takeout archive 

After we have had a look at the structure of the takeout archive, we can build some scripts to translate the content of the JSON post description into a format that is suitable for import into the target system, which in our case is Diaspora*.

The following script is a proof of concept conversion of a single post file from the takeout archive to text string that is suitable for upload to a Diaspora* server using the diaspy API.

Images are more challenging and will be handled separately in a later episode. There is also no verification on whether the original post had public visibility and should be re-posted publicly.

The main focus is on the parse_post and format_post methods. The purpose of the parse_post method is to extract the desired information from the JSON representation of a post, while the format_post method uses this data to format the input text needed to create a more or less equivalent post.

While the the post content text in the google+ takeout archive is formatted in pseudo-HTML, Diaspora* post are formatted in Markdown. In order to convert the HTML input to Markdown output, we can use the html2text Python library.

Given the difference in formatting and conventions, there is really no right or wrong way to reformat each post, but a matter of choice.

The choices made here are:

  • If the original post contained text, the text is included at the top of the post with minimal formatting and any URL links stripped out. Google+ posts may include +<username> reference which may look odd. Hashtags should be automatically re-hashtagified on the new system, as long as it uses the hashtag convention.
  • The post includes a series of static hashtags which identify it as a archived, re-posted from G+. Additional hashtags can be generated during the parsing process, e.g. to identify re-shares of photos
  • The original post date and optional community or collection names are included with each post, as we intend to make it obvious that this is a re-posted archive and not a transparent migration.
  • Link attachments are added at the end and should be rendered as a proper link attachment with preview snipped and image if supported - presumably by using something like the OpenGraph markup annotations of the linked page.
  • Deliberately not include any data which results from post activity by other users including likes or re-shares. The only exception is that if a re-shared post includes and external link, this link is included in the post with a "hat tip" to the original poster using their G+ display name at the time of export.

The functionality to post to Diaspora* is included at this time merely as a demonstration that this can indeed work and is not intended to be used without additional operational safeguards.

#!/usr/bin/env python

import datetime
import json
import sys

import dateutil.parser
import diaspy
import html2text

SERVER = '<your diaspora server URL>'
USERNAME = '<your diaspora username>'
PASSWORD = '<not really a good idea...>'

TOOL_NAME = 'G+ repost'
HASHTAGS = ['repost', 'gplusarchive', 'googleplus', 'gplusrefugees', 'plexodus']

def post_to_diaspora(content, filenames=[]):
  c = diaspy.connection.Connection(pod = SERVER,
                                   username = USERNAME,
                                   password = PASSWORD)
  stream = diaspy.streams.Stream(c), provider_display_name = TOOL_NAME)

def format_post(content, link, hashtags, post_date, post_context):
    output = []

    if content:
        converter = html2text.HTML2Text()
        converter.ignore_links = True
        converter.body_width = 0
    if hashtags:
        output.append(' '.join(('#' + tag for tag in hashtags)))

    if post_date:
        output.append('Originally posted on Google+ on %s%s' 
                      % (post_date.strftime('%a %b %d, %Y'),
                         '  ( ' + post_context + ')' if post_context else ''))

    if link:

    return '\n'.join(output)

def parse_post(post_json):
    post_date = dateutil.parser.parse(post_json['creationTime'])
    content = post_json['content'] if 'content' in post_json else ''
    link = post_json['link']['url'] if 'link' in post_json else ''

    hashtags = HASHTAGS

    # TODO: Dealing with images later...
    if 'album' in post_json or 'media' in post_json:
        hashtags = hashtags + ['photo', 'photography']

    # If a shared post contains a link, extract that link
    # and give credit to original poster.
    if 'resharedPost' in post_json and 'link' in post_json['resharedPost']:
        link = post_json['resharedPost']['link']['url']
        content = content + ' - H/t to ' + post_json['resharedPost']['author']['displayName']

    acl = post_json['postAcl']
    post_context = ''
    if 'communityAcl' in acl:
        post_context = acl['communityAcl']['community']['displayName']

    return format_post(content, link, hashtags, post_date, post_context)

# ----------------------
filename = sys.argv[1]
post_json = json.load(open(filename))

if len(sys.argv) > 2 and sys.argv[2] == 'repost':
    print ('posting to %s as %s' % (SERVER, USERNAME))