-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
499 lines (450 loc) · 17.2 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# IMPORT LIBRARIES
# Streamlit for UI
import streamlit as st
#Gql for GraphQL queries
from gql import gql
#SpecklePy stuff
from specklepy.api.credentials import get_account_from_token
from specklepy.api.client import SpeckleClient
#json when dealing with received objects
import json
# Notion API requests
import requests
#imagehandler to upload image as url to notion
from imageHandler import uploadImage, downloadImage
from PIL import Image
#--------------------------
#PAGE CONFIG
st.set_page_config(
page_title="Speckle Comments to Notion",
page_icon="💬"
)
#--------------------------
#--------------------------
#SIDEBAR
#import logo
logo = Image.open("app-logo.png")
st.sidebar.image(logo,caption="Connects your Speckle Comments to Notion Database")
#sidebar title
st.sidebar.title("Speckle Comments to Notion")
#page names as a list
pages = ["Home", "App"]
#radio for the page navigation
nav = st.sidebar.radio(label="Navigation", options=pages, index=0)
#--------------------------
#HOMEPAGE
if nav == pages[0]:
#--------------------------
#CONTAINERS
header = st.container()
about_app = st.container()
hack_inspiration = st.container()
what_it_does = st.container()
how_to_use = st.container()
tech_stack = st.container()
#--------------------------
#--------------------------
#PAGE TITLE
with header:
st.title("Speckle Comments 💬 to Notion📄")
#--------------------------
#--------------------------
#ABOUT APP
with about_app.expander("About this app🔽", expanded=True):
st.markdown(
"""
This app sends your Speckle comments into a given Notion database and assigns Speckle attributes as properties of Notion pages.
Our main aim was to create a bidirectional link between two applications so we can leverage the best out of both.
Take a look 👀
"""
)
#--------------------------
#--------------------------
with hack_inspiration:
st.subheader("Inspiration 🌹")
st.markdown(
"""
Recently added **Comments** feature on Speckle has broken new grounds but since it's still being developed, it has its own limitations.
One limitation we saw was assigning statuses to comments and tracking of them. We thought, "*Notion is really flexible and powerful in this area,
and its used by a lot of architecture offices, maybe we can track their status there. Why not integrate the two?*".
With this app, you send your Speckle comments to Notion and track their status there. Once its status is "Archived" in Notion, it'll be archived in Speckle as well.
"""
)
#--------------------------
#--------------------------
#HOW TO USE
with how_to_use:
st.subheader("How to use🤔")
st.markdown(
"""
If you want to learn how to use it, take a look at the video below👇
"""
)
st.video("https://youtu.be/WQoxlD1S3p4",)
#--------------------------
#--------------------------
with what_it_does:
st.subheader("What does it do? 😏")
st.markdown(
"""
It takes comments from an existing Speckle stream🌊 and sends it to Notion with the properties:
- ``Comment ID 🆔``
- ``Author ✍``
- ``Camera Position 📹``
- ``Created At 📅``
It sets the page cover as the `Screenshot 📷` of comment
And it also creates an iframe with a ``Speckle Viewer 👁🗨`` embedded.
Finally assigns status ``Not Started 🔴``
In **Notion** you can track and update the comment and when the comments is R esolved and **Archived 📦** in Notion,
it will also be archived in Speckle🔹.
"""
)
#--------------------------
with tech_stack:
st.subheader("Technologies Used 🤓")
st.markdown(
"""
- SpecklePy 🐍
- Notion API
- Streamlit 👑 (as the UI)
- GraphQL Queries
- Imgur API 🖼
"""
)
#INPUTS PAGE
if nav == pages[1]:
#--------------------------
#CONTAINERS
header = st.container()
speckle_inputs = st.container()
notion_inputs = st.container()
run = st.container()
#--------------------------
#--------------------------
#HEADER
#Page Header
with header:
st.title("App 💬")
#--------------------------
#--------------------------#--------------------------#--------------------------#--------------------------
#🔹SPECKLE INPUTS
with speckle_inputs:
st.subheader("Speckle🔹")
#-------
#Columns for inputs
serverCol, tokenCol = st.columns([1,3])
#User Input boxes
speckleServer = serverCol.text_input("Server URL", "speckle.xyz", help="Speckle server to connect.")
speckleToken = tokenCol.text_input("Speckle token", "c3ec1797cca318cc2fd96822dad37cc6f9823c52ca", help="If you don't know how to get your token, take a look at this [link](https://speckle.guide/dev/tokens.html)👈")
#-------
#-------
#CLIENT
client = SpeckleClient(host=speckleServer)
#Get account from Token
account = get_account_from_token(speckleToken, speckleServer)
#Authenticate
client.authenticate_with_account(account)
#-------
#-------
#Streams List👇
streams = client.stream.list()
#Get Stream Names
streamNames = [s.name for s in streams]
#🔽DROPDOWN for stream selection🔽
sName = st.selectbox(label="Select your stream", options=streamNames, help="Select your stream from the dropdown")
#✅SELECTED STREAM ✅
stream = client.stream.search(sName)[0]
#-------
#--------------------------
#--------------------------
#CACHE
@st.cache
# Function for receiving comments🛠
def get_comments(stream):
query = gql(
"""{
comments(streamId:\""""
+ stream.id +
"""\") {
items {
text
id
authorId
createdAt
data
resources{
resourceId
}
archived
screenshot
}
}
}"""
)
# Making query to Speckle
comments = client.execute_query(query=query)
return comments
#--------------------------
#get user info
def get_user_info(authorId):
query = gql(
"""{
user(id: \""""
+ authorId +
"""\") {
name
}
}"""
)
try:
user_name = client.execute_query(query=query)
return user_name['user']['name']
except:
return authorId
#--------------------------
# archive comment
def archiveSpeckleComment(streamId, commentId):
query = gql(
"""mutation {
commentArchive(
streamId:\""""
+ streamId +
"""\"
commentId:\""""
+ commentId +
"""\"
archived:true)
}"""
)
client.execute_query(query)
st.write('Archive comment: ' + commentId)
#--------------------------
#--------------------------
# NOTION ⬛ INPUTS
with notion_inputs:
st.subheader('Notion📄')
notion_token = st.text_input('Notion Integration Token', 'secret_P6HNSC8hX5gaQVkLSm5XlzR1KD61OMJDltOnVPWEE3Z', help='Learn how to get your Notion Token')
notion_db_id = st.text_input('Database Id 🆔', '26d224183bfc488181a37cd2d74be1bf', help='Learn more about how to get your database id')
#--------------------------
#--------------------------
#HEADERS
headers = {
"Accept": "application/json",
"Notion-Version": "2022-02-22",
"Content-Type": "application/json",
"Authorization": "Bearer "+notion_token
}
#--------------------------
#--------------------------
#🔨NOTION FUNCTIONS 🔨
#CACHE NOTION
#@st.cache
# Database Query
def queryDatabase(databaseId, headers):
url = f"https://api.notion.com/v1/databases/{databaseId}/query"
res = requests.request("POST", url, headers=headers)
data = res.json()
return res , data
# Get list of Issues already in Notion
def getExistingIssueIds(jsonData):
existingIssuesIds = dict()
pages = jsonData['results']
for p in pages:
props = p['properties']
# If existing page doesn't contain an Id just skip
try:
id = props['Id']['rich_text'][0]['plain_text']
except:
continue
issue_id = p['id']
status_name = props['Status']['select']['name']
status_color = props['Status']['select']['color']
existingIssuesIds[id] = (issue_id, status_name, status_color)
return existingIssuesIds
# Define page layout
def definePage(databaseId, comment_info, author, status_name, status_color, img_url):
# Join cam postion into comma separated string
camPos = ",".join([str(pos) for pos in [comment_info["data"]["camPos"]]])
# Construct embed link
commitURL = comment_info["resources"][0]["resourceId"]
embedUrl = f"https://speckle.xyz/embed?stream={stream.id}&commit={commitURL}&c={camPos}"
# define page payload
payload = {
"children":[{
"object": "block",
"id": "a7e10d37-4652-4573-a62a-3f3b3a2a648f",
"has_children": False,
"archived": False,
"type": "embed",
"embed": {
"caption": [],
"url": embedUrl
}
}],
"parent": {
"type": "database_id",
"database_id": databaseId
},
"properties": {
"Author Id": {
"id": "%3Dazv",
"type": "rich_text",
"rich_text": [
{
"type": "text",
"text": {
"content": author,
"link": None
},
"annotations": {
"bold": False,
"italic": False,
"strikethrough": False,
"underline": False,
"code": False,
"color": "default"
},
"plain_text": author,
"href": None
}
]
},
"Id": {
"id": "Ker%7B",
"type": "rich_text",
"rich_text": [
{
"type": "text",
"text": {
"content": comment_info['id'],
"link": None
},
"annotations": {
"bold": False,
"italic": False,
"strikethrough": False,
"underline": False,
"code": False,
"color": "default"
},
"plain_text": comment_info['id'],
"href": None
}
]
},
"Status": {
"id": "VlA%5B",
"type": "select",
"select": {
"id": "1",
"name": status_name,
"color": status_color
}
},
"Camera Position": {
"id": "xd%3C%5C",
"type": "rich_text",
"rich_text": [
{
"type": "text",
"text": {
"content": camPos,
"link": None
},
"annotations": {
"bold": False,
"italic": False,
"strikethrough": False,
"underline": False,
"code": False,
"color": "default"
},
"plain_text": camPos,
"href": None
}
]
},
"Created At": {
"id": "%7B%3Ai%60",
"type": "date",
"date": {
"start": comment_info['createdAt']
}
},
"Name": {
"id": "title",
"type": "title",
"title": [
{
"type": "text",
"text": {
"content": comment_info['text'],
"link": None
},
"annotations": {
"bold": False,
"italic": False,
"strikethrough": False,
"underline": False,
"code": False,
"color": "default"
},
"plain_text": comment_info['text'],
"href": None
}
]
}
},
"cover": {
"type": "external",
"external": {"url": img_url }
}
}
return payload
# Create a Page 📄
def createPage(databaseId, headers, comment_info, author):
url = "https://api.notion.com/v1/pages"
img_path = downloadImage(img_string=comment_info['screenshot'], img_name=comment_info['id'])
image = uploadImage(img_path=img_path)
payload = definePage(databaseId=databaseId, comment_info=comment_info, author=author, status_name='Not started', status_color='red', img_url=image['link'])
response = requests.post(url, json=payload, headers=headers)
st.write('Created comment: ' + comment_info['id'])
#st.write(response.text)
# Update a Page 📄
def updatePage(databaseId, headers, comment_info, author, page_info):
url = f"https://api.notion.com/v1/pages/{page_info[0]}"
payload = definePage(databaseId=databaseId, comment_info=comment_info, author=author, status_name=page_info[1], status_color=page_info[2], img_url=None)
response = requests.patch(url, json=payload, headers=headers)
st.write('Updated comment: ' + comment_info['id'])
#st.write(response.text)
#--------------------------
#RUN BUTTON 🏃♂️💨
#if button clicked run app otherwise don't
with run:
run_app = st.button("RUN 🚀")
#--------------------------
if run_app:
#💬COMMENTS 💬
#💬Get Comments From Stream💬
comments = get_comments(stream=stream)
comment_info_list = comments['comments']['items']
# Get pages already in Notion database
res, jsonData = queryDatabase(databaseId=notion_db_id, headers=headers)
# Get Ids of existing issues and pages
issueIds = getExistingIssueIds(jsonData)
st.write('Number of comments: ' + str(len(comment_info_list)))
# Go through comment list from Speckle
# If comment already in Notion then update else create new
for com in comment_info_list:
user = get_user_info(com['authorId'])
if com['id'] in issueIds:
if issueIds[com['id']][1] == 'Archived':
archiveSpeckleComment(streamId=stream.id, commentId=com['id'])
else:
updatePage(databaseId=notion_db_id, headers=headers, comment_info=com, author=user, page_info=issueIds[com['id']])
else:
createPage(databaseId=notion_db_id, headers=headers, comment_info=com, author=user)
#n_db_res, n_db_data = queryDatabase(databaseId=notion_db_id, headers=headers)
#st.write(n_db_data['results'][0])
#--------------------------
#--------------------------#--------------------------#--------------------------#--------------------------