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))

Sunday, October 28, 2018

Google+ Migration - Part II: Understanding the Takeout Archive

<- Part I: Takeout

Once we the takeout archive has been successfully generated we can download and unarchive/extract it to our local disks. At that point we should find a new directory called Takeout with the Google+ posts being located at the following directory location: Takeout/Google+ Stream/Posts.

This posts directory contains 3 types of files:
  • File containing data for each post in JSON format
  • Media files of images or videos uploaded and attached to posts, for example in JPG format
  • Metadata files for each media-file in CSV  forma with an additional extensions of .metadata.csv
The filenames are generated as part of the takeout archive generation process with the following conventions: the post filenames are structured as a date in YYYYMMDD format followed by a snippet of of the post text or the word "Post" if there is not text. The media filenames seem to be close to the original names of the files when they were uploaded.

Whenever a filename is not unique, an additional count is added like in these examples:

20180808 - Post(1).json
20180808 - Post(2).json
20180808 - Post(3).json
20180808 - Post.json

Filenames which contain unicode characters that are not in the base ASCII may not be correctly represented on all platforms and in particular appear corrupted in the .tgz archive. For the cases which I have been able to test, the default .zip encoded archive seems to handle unicode filenames correctly.

Each of the .json post files contains a JSON object with different named sub-objects which can themselves again be objects, lists of objects or elementary types like strings or numbers.

Based on the data which I have been able to analyze from my post archive, the post JSON object contains the following relevant sub-objects:
  • author - information about the user who created the post. In a personal takeout archive, this is always the same user.
  • creationTime and updateTime - timestamp of when post was originally created or last updated, respectively
  • content - text of the post in HTML like formatting
  • link, album, media or resharedPost etc. - post attachments of a certain type
  • location - location tag associated with post
  • plusOnes - record of users who have "plussed" the post
  • reshares - records of users who have shared the post
  • comments - record of comments, including comment author info as well as comment content
  • resourceName - unique ID of the post (also available for users, media and other objects)
  • postAcl - visibility of Post - e.g. public, part of a community or visible only to some circles or users.
In particular this list is missing the representation for collections or other post attachments like pools or events, as there are no examples for this among my posts.

An example JSON for a very simple post consisting of a single unformatted text line, an attached photo and a location tag - without any recorded post interactions:

  "url": "",
  "creationTime": "2018-07-15 20:43:51+0000",
  "updateTime": "2018-07-15 20:43:51+0000",
  "author": {
  "content": "1 WTC",
  "media": {
    "url": "
    "contentType": "image/*",
    "width": 2838,
    "height": 3785,
    "description": "1 WTC",
    "resourceName": "media/CixBRjFRaXBNRUpjaXh6QTRyckdjNE5Nbmx5blVwTTBjd2lIblh3VWFCek0zMA\u003d\u003d"
  "location": {
    "latitude": 40.7331168,
    "longitude": -74.0108977,
    "displayName": "Hudson River Park Trust",
    "physicalAddress": "353 West St, New York, NY 10011, USA"
  "resourceName": "users/117832126248716550930/posts/UgjyOA5tNBvbgHgCoAEC",
  "postAcl": {
    "visibleToStandardAcl": {
      "circles": [{
        "type": "CIRCLE_TYPE_PUBLIC"

JSON is a simple standard data format that can easily be processed programmatically and many supporting libraries already exist. The Python standard library contains a module to parse JSON files and expose the data as native Python data objects to the code for further inspection and processing.

For example this simple Python program below can be used to determine whether a post has public visibility or not:


import json
import sys

def is_public(acl):
  """Return True, if access control object contains the PUBLIC pseudo-circle."""
  if ('visibleToStandardAcl' in acl
      and 'circles' in acl['visibleToStandardAcl']):
    for circle in acl['visibleToStandardAcl']['circles']:
      if circle['type'] == 'CIRCLE_TYPE_PUBLIC':
        return True
  return False

# filter out only the posts which have public visibility.
for filename in sys.argv[1:]:
  post = json.load(open(filename))
  if is_public(post['postAcl']):
    print (filename)

Running this as ./ ~/Download/Takeout/Google+\ Stream/Posts/*.json would return the list of filenames which contain the publicly visible posts only. By successfully parsing all the .json files in the (i.e. without trowing any errors), we can also convince ourselves that the archive contains data in syntactically valid JSON format.

Sunday, October 21, 2018

Google+ Migration - Part I: Takeout

For the last 7 years, I have been using Google+ as my primary social sharing site - with
automated link-sharing to Twitter. With Google+ going away, I am looking to migrate my public postings to a new site, where they can be presented in a similar way. As the target for the migration, I have chosen a local community-operated pod of the diaspora* network.

Migrating social media-data is particularly challenging. They are by definition an amalgamation of data from different sources: links, re-sharing, likes comments etc. - all potentially created by different users of the original social sharing platform. Also contrary to other data-sets (e.g. contact-lists, calendars or spreadsheets), there are no established, standardized data formats for exchanging social networking site activity in a platform independent way.

Without being an expert in copyright and data protection law, I am taking a very conservative approach to ownership and consent. Users of the original Google+ site were explicitly ok with the following cross-user interactions from the perspective of my post-stream:

  • re-sharing post of other users (while respecting the original scope)
  • other users liking ("plussing") my posts
  • other users commenting on my posts

Since none of these other users have ever granted my an explicit permission to replicate this content in a new form on another platform, I will only replicate my original content without any interactions, but in addition to public posts also include posts to communities, which I consider public. The purpose of this tutorial is to present some tools and methods that could be used to process and select data in a different way to implement a different policy.

For the technicalities of migration, I am making the following assumptions assumptions:

  • as input, only rely on data that is contained in the takeout-archive. This way the migration could be repeated after the original Google+ site is now longer accessible.
  • use the Python programming language for parsing, processing and re-formatting of the data.
  • use a bot with a Python API-library for diaspora* to repost (very slowly!) to the new target system.
While Python is highly portable, any examples and instructions in this tutorial will assume a unix-like operating system an be tested in particular on a current Debian GNU/Linux based system.

Ordering Takeout

For over 10 years, a Google team calling itself the Data Liberation Front, has been working on a promise that users should be able to efficiently extract any of the data they create online with Google services and take them elsewhere. The resulting service is

In order to get an archive suitable for processing, we need to request a takeout archive of the Google+ stream data in JSON format. Here are some basic instructions on how to request a new takeout archive.

For the purpose of this migration, we only need to select "Google+ Stream" in data selection. However, we need to open the extension panel and select JSON format instead of the default HTML. While the HTML export only contains the information necessary to display each post, the JSON export contains additional meta-data like access-rights in an easily machine readable format.

Given the high load on the service right now, archive creation for large streams can take a while or be incomplete. We should expect this process to become more reliable again in the next few weeks.

The next step will be to understand the structure of the data in the takeout archive.