Skip to content

Commit e1caf2b

Browse files
committed
Add slack data importer.
This importer is more comprehensive than the existing one.
1 parent 09060af commit e1caf2b

File tree

1 file changed

+290
-0
lines changed

1 file changed

+290
-0
lines changed
Lines changed: 290 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
#!/usr/bin/env python
2+
import os
3+
import json
4+
import hashlib
5+
import sys
6+
import argparse
7+
import shutil
8+
import subprocess
9+
import zipfile
10+
11+
12+
# Transported from https://github.com/zulip/zulip/blob/master/zerver/lib/export.py
13+
def rm_tree(path):
14+
# type: (str) -> None
15+
if os.path.exists(path):
16+
shutil.rmtree(path)
17+
18+
def users2zerver_userprofile(slack_dir, realm_id, timestamp, domain_name):
19+
# type: () -> None
20+
print('######### IMPORTING USERS STARTED #########\n')
21+
users = json.load(open(slack_dir + '/users.json'))
22+
zerver_userprofile = []
23+
added_users = {}
24+
user_id_count = 1
25+
for user in users:
26+
slack_user_id = user['id']
27+
profile = user['profile']
28+
DESKTOP_NOTIFICATION = True
29+
if 'email' not in profile:
30+
email = (hashlib.blake2b(user['real_name'].encode()).hexdigest() +
31+
"@%s" % (domain_name))
32+
userprofile = dict(
33+
enable_desktop_notifications=DESKTOP_NOTIFICATION,
34+
is_staff=user['is_admin'],
35+
# avatar_source='G',
36+
is_bot=user['is_bot'],
37+
avatar_version=1,
38+
autoscroll_forever=False,
39+
default_desktop_notifications=True,
40+
timezone=user.get("tz", ""),
41+
default_sending_stream=None,
42+
enable_offline_email_notifications=True,
43+
user_permissions=[], # TODO ???
44+
is_mirror_dummy=False,
45+
pointer=-1,
46+
default_events_register_stream=None,
47+
is_realm_admin=user['is_owner'],
48+
invites_granted=0,
49+
enter_sends=True,
50+
bot_type=1 if user['is_bot'] else None,
51+
enable_stream_sounds=False,
52+
is_api_super_user=False,
53+
rate_limits="",
54+
last_login=timestamp,
55+
tos_version=None,
56+
default_all_public_streams=False,
57+
full_name=user['real_name'],
58+
twenty_four_hour_time=False,
59+
groups=[], # TODO
60+
muted_topics=[],
61+
enable_online_push_notifications=False,
62+
alert_words="[]",
63+
# bot_owner=None, TODO
64+
short_name=user['name'],
65+
enable_offline_push_notifications=True,
66+
left_side_userlist=False,
67+
enable_stream_desktop_notifications=False,
68+
enable_digest_emails=True,
69+
last_pointer_updater="",
70+
email=email,
71+
date_joined=timestamp,
72+
last_reminder=timestamp,
73+
is_superuser=False,
74+
tutorial_status="T",
75+
default_language="en",
76+
enable_sounds=True,
77+
pm_content_in_desktop_notifications=True,
78+
is_active=user['deleted'],
79+
onboarding_steps="[]",
80+
emojiset="google",
81+
emoji_alt_code=False,
82+
realm=realm_id, # TODO
83+
# harcoded as per https://github.com/zulip/zulip/blob/e1498988d9094961e6f9988fb308b3e7310a8e74/zerver/migrations/0059_userprofile_quota.py#L18
84+
quota=1073741824,
85+
invites_used=0,
86+
id=user_id_count)
87+
88+
# TODO map the avatar
89+
# zerver auto-infer the url from Gravatar instead of from a specified
90+
# url; zerver.lib.avatar needs to be patched
91+
# profile['image_32'], Slack has 24, 32, 48, 72, 192, 512 size range
92+
93+
zerver_userprofile.append(userprofile)
94+
added_users[slack_user_id] = user_id_count
95+
user_id_count += 1
96+
print(u"{} -> {}\nCreated\n".format(user['name'], userprofile['email']))
97+
print('######### IMPORTING USERS FINISHED #########\n')
98+
return zerver_userprofile, added_users
99+
100+
def channels2zerver_stream(slack_dir, realm_id, added_users):
101+
# type: (Dict[str, Dict[str, str]]) -> None
102+
print('######### IMPORTING CHANNELS STARTED #########\n')
103+
channels = json.load(open(slack_dir + '/channels.json'))
104+
added_channels = {}
105+
zerver_stream = []
106+
stream_id_count = 1
107+
zerver_subscription = []
108+
zerver_recipient = []
109+
for channel in channels:
110+
# slack_channel_id = channel['id']
111+
112+
# map Slack's topic and purpose content into Zulip's stream description.
113+
# WARN This mapping is lossy since the topic.creator, topic.last_set,
114+
# purpose.creator, purpose.last_set fields are not preserved.
115+
description = "topic: {}\npurpose: {}".format(channel["topic"]["value"],
116+
channel["purpose"]["value"])
117+
118+
# construct the stream object and append it to zerver_stream
119+
stream = dict(
120+
realm=realm_id,
121+
name=channel["name"],
122+
deactivated=channel["is_archived"],
123+
description=description,
124+
invite_only=not channel["is_general"],
125+
date_created=channel["created"],
126+
id=stream_id_count)
127+
zerver_stream.append(stream)
128+
added_channels[stream['name']] = stream_id_count
129+
130+
# construct the subscription object and append it to zerver_subscription
131+
for member in channel['members']:
132+
sub = dict(
133+
recipient=added_users[member],
134+
notifications=False,
135+
color="#c2c2c2",
136+
desktop_notifications=True,
137+
pin_to_top=False,
138+
in_home_view=True,
139+
active=True,
140+
user_profile=added_users[member],
141+
id=stream_id_count) # TODO is this the correct interpretation?
142+
zerver_subscription.append(sub)
143+
144+
# recipient
145+
# type_id's
146+
# 1: private message
147+
# 2: stream
148+
# 3: huddle
149+
# TOODO currently the goal is to map Slack's standard export
150+
# This defaults to 2
151+
# TOODO do private message subscriptions between each users have to
152+
# be generated from scratch?
153+
rcpt = dict(
154+
type=2,
155+
type_id=stream_id_count,
156+
id=added_users[member])
157+
zerver_recipient.append(rcpt)
158+
159+
stream_id_count += 1
160+
print(u"{} -> created\n".format(channel['name']))
161+
162+
# TODO map Slack's pins to Zulip's stars
163+
# There is the security model that Slack's pins are known to the team owner
164+
# as evident from where it is stored at (channels)
165+
# "pins": [
166+
# {
167+
# "id": "1444755381.000003",
168+
# "type": "C",
169+
# "user": "U061A5N1G",
170+
# "owner": "U061A5N1G",
171+
# "created": "1444755463"
172+
# }
173+
# ],
174+
print('######### IMPORTING STREAMS FINISHED #########\n')
175+
return zerver_stream, added_channels, zerver_subscription, zerver_recipient
176+
177+
def channelmessage2zerver_message(slack_dir, channel, added_users, added_channels):
178+
json_names = os.listdir(slack_dir + '/' + channel)
179+
zerver_message = []
180+
msg_id_count = 1
181+
for json_name in json_names:
182+
msgs = json.load(open(slack_dir + '/%s/%s' % (channel, json_name)))
183+
for msg in msgs:
184+
text = msg['text']
185+
zulip_message = dict(
186+
sending_client=1,
187+
rendered_content_version=1, # TODO ?? doublecheck
188+
has_image=False, # TODO
189+
subject=channel, # TODO default subject to channel name; Slack has subtype and type
190+
pub_date=msg['ts'],
191+
id=msg_id_count,
192+
has_attachment=False, # attachment will be posted in the subsequent message; this is how Slack does it, less like email
193+
edit_history=None,
194+
sender=added_users[msg['user']], # map slack id to zulip id
195+
content=text, # TODO sanitize slack text, which contains <@msg['user']|short_name>
196+
rendered_content=text, # TODO slack doesn't cache this, check whether text is rendered
197+
recipient=added_channels[channel],
198+
last_edit_time=None,
199+
has_link=False) # TODO
200+
zerver_message.append(zulip_message)
201+
return zerver_message
202+
203+
def main(slack_zip_file):
204+
# type: (str) -> None
205+
206+
slack_dir = slack_zip_file.replace('.zip', '')
207+
with zipfile.ZipFile(slack_zip_file, 'r') as zip_ref:
208+
zip_ref.extractall(slack_dir)
209+
210+
from datetime import datetime
211+
# TODO fetch realm config from zulip config
212+
DOMAIN_NAME = "zulipchat.com"
213+
REALM_ID = 1
214+
REALM_NAME = "FleshEatingBatswithFangs"
215+
NOW = datetime.utcnow().timestamp()
216+
zerver_realm_skeleton = json.load(open('zerver_realm_skeleton.json'))
217+
zerver_realm_skeleton[0]['id'] = REALM_ID
218+
zerver_realm_skeleton[0]['string_id'] = 'zulip' # subdomain / short_name of realm
219+
zerver_realm_skeleton[0]['name'] = REALM_NAME
220+
zerver_realm_skeleton[0]['date_created'] = NOW
221+
222+
# Make sure the directory output is clean
223+
output_dir = 'zulip_data'
224+
rm_tree(output_dir)
225+
os.makedirs(output_dir)
226+
227+
realm = dict(zerver_defaultstream=[], # TODO
228+
zerver_client=[{"name": "populate_db", "id": 1},
229+
{"name": "website", "id": 2},
230+
{"name": "API", "id": 3}],
231+
zerver_userpresence=[], # TODO
232+
zerver_userprofile_mirrordummy=[],
233+
zerver_realmdomain=[{"realm": REALM_ID,
234+
"allow_subdomains": False,
235+
"domain": DOMAIN_NAME,
236+
"id": REALM_ID}],
237+
zerver_useractivity=[],
238+
zerver_realm=zerver_realm_skeleton,
239+
zerver_huddle=[], # TODO
240+
zerver_userprofile_crossrealm=[], # TODO
241+
zerver_useractivityinterval=[],
242+
zerver_realmfilter=[],
243+
zerver_realmemoji=[])
244+
245+
zerver_userprofile, added_users = users2zerver_userprofile(slack_dir,
246+
REALM_ID,
247+
int(NOW),
248+
DOMAIN_NAME)
249+
realm['zerver_userprofile'] = zerver_userprofile
250+
251+
zerver_stream, added_channels, zerver_subscription, zerver_recipient = channels2zerver_stream(slack_dir, REALM_ID, added_users)
252+
realm['zerver_stream'] = zerver_stream
253+
realm['zerver_subscription'] = zerver_subscription
254+
realm['zerver_recipient'] = zerver_recipient
255+
# IO
256+
json.dump(realm, open(output_dir + '/realm.json', 'w'))
257+
258+
# now for message.json
259+
message_json = {}
260+
zerver_message = []
261+
# TODO map zerver_usermessage
262+
for channel in added_channels.keys():
263+
zerver_message.append(channelmessage2zerver_message(slack_dir, channel,
264+
added_users, added_channels))
265+
message_json['zerver_message'] = zerver_message
266+
# IO
267+
json.dump(message_json, open(output_dir + '/message.json', 'w'))
268+
269+
# TODO
270+
# attachments
271+
272+
# remove slack dir
273+
rm_tree(slack_dir)
274+
275+
# compress the folder
276+
subprocess.check_call(['zip', '-r', output_dir + '.zip', output_dir])
277+
278+
# remove zulip dir
279+
rm_tree(output_dir)
280+
281+
sys.exit(0)
282+
283+
if __name__ == '__main__':
284+
# from django.conf import settings
285+
# settings_module = "settings.py"
286+
# os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
287+
description = ("script to convert Slack export data into Zulip export data")
288+
parser = argparse.ArgumentParser(description=description)
289+
slack_zip_file = sys.argv[1]
290+
main(slack_zip_file)

0 commit comments

Comments
 (0)