git ssb

0+

Grey the earthling / scuttleblog



Tree: 0cc15bcd9a37b318d9087f8f0a7e09fee879a308

Files: 0cc15bcd9a37b318d9087f8f0a7e09fee879a308 / scuttleblog.py

5914 bytesRaw
1#!/usr/bin/python3
2
3__copyright__ = """
4
5 Scuttleblog
6
7 Copyright (C) 2017 Greg K Nicholson
8
9 This program is free software:
10 you can redistribute it and/or modify it
11 under the terms of the GNU Affero General Public License
12 as published by the Free Software Foundation,
13 either version 3 of the License,
14 or (at your option) any later version.
15
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY;
18 without even the implied warranty
19 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
20 See the GNU Affero General Public License for more details.
21
22 You should have received a copy
23 of the GNU Affero General Public License
24 along with this program.
25 If not, see <https://www.gnu.org/licenses/>.
26
27"""
28
29import datetime
30import json
31import os
32import re
33import time
34import subprocess
35
36import conf
37
38scuttleblog_dir = os.path.dirname(__file__)
39
40def run_sbot():
41 for attempt in range(100):
42 try:
43 subprocess.check_output(['sbot', 'status'])
44 except:
45 pid = subprocess.Popen(['sbot', 'server']).pid
46 time.sleep(1)
47 else:
48 break
49
50def get_user_posts(ssb_userid):
51 user_posts_args = ['sbot', 'createUserStream', '--id', ssb_userid]
52 json_posts_args = ['json', '--group', \
53 '-c', 'this.value.content.type == "post"', \
54 '-c', 'this.value.content.text != null', \
55 '-c', 'this.value.content.text != ""', \
56 '-c', 'this.value.content.root == null']
57 user_posts_stream = subprocess.Popen(user_posts_args,
58 stdout = subprocess.PIPE)
59 user_posts_json = subprocess.check_output(json_posts_args,
60 stdin = user_posts_stream.stdout)
61 user_posts = json.loads(user_posts_json)
62 return user_posts
63
64def define_post_text(text):
65 text = text.strip()
66 title = text.splitlines()[0]
67 maxlength = 140
68 ellipsis = '...'
69 if len(title) > maxlength:
70 title = title[:maxlength].rsplit(' ', 1)[0] + ellipsis
71 body = text
72 else:
73 if len(text.splitlines()) > 1:
74 body = ''.join(text.splitlines(keepends=True)[1:]).strip()
75 else:
76 body = ''
77 title = re.sub('^#+\s+', '', title)
78 return {'title': title, 'body': body}
79
80def build_post_structure(p):
81 post = {}
82 post['frontmatter'] = {}
83 post['frontmatter']['key'] = p['key']
84 post['frontmatter']['title'] = define_post_text(
85 p['value']['content']['text'])['title']
86 time = datetime.datetime.fromtimestamp(int(p['value']['timestamp']
87 / 1000),
88 datetime.timezone.utc)
89 post['frontmatter']['date'] = time.strftime('%Y-%m-%dT%H:%M:%SZ')
90 post['frontmatter']['sequence'] = p['value']['sequence']
91 post['body'] = define_post_text(p['value']['content']['text'])['body']
92 return (post)
93
94def format_post_file(post):
95 content = ''
96 content += str(json.dumps(post['frontmatter'], indent = 4))
97 content += '\n\n'
98 content += str(post['body'])
99 return content
100
101def define_post_filename(post):
102 folder = 'hugo/content/posts'
103 slug = str(post['frontmatter']['sequence'])
104 filetype = 'md'
105 return folder + '/' + slug + '.' + filetype
106
107def write_post_file(post):
108 os.makedirs(os.path.dirname(define_post_filename(post)), exist_ok=True)
109 with open(define_post_filename(post), 'w') as f:
110 f.write (format_post_file(post))
111
112def write_posts_from_user(ssb_userid):
113 posts = get_user_posts(ssb_userid)
114 for post in posts:
115 write_post_file(build_post_structure(post))
116
117
118def get_user_metadata(ssb_userid):
119 user_metadata_args = ['sbot', 'links',
120 '--source', ssb_userid,
121 '--dest', ssb_userid,
122 '--rel', 'about',
123 '--values']
124 json_metadata_args = ['json', '--deep-merge',
125 '-c', 'this.value.content.type == "about"']
126 user_metadata_stream = subprocess.Popen(user_metadata_args,
127 stdout = subprocess.PIPE)
128 user_metadata_json = subprocess.check_output(json_metadata_args,
129 stdin = user_metadata_stream.stdout)
130 user_metadata = json.loads(user_metadata_json)
131 return user_metadata
132
133def check_hugo_theme(theme, theme_clone_url):
134 hugo_theme_dir = os.path.join(scuttleblog_dir, 'hugo', 'themes', theme)
135 if not os.path.isdir(hugo_theme_dir):
136 subprocess.run(['git', 'submodule', 'add', '-f',
137 theme_clone_url, hugo_theme_dir])
138
139def build_hugo_config(m):
140 hugo_config = {}
141 hugo_config['baseurl'] = conf.hugo_baseurl
142 hugo_config['theme'] = conf.hugo_theme
143 hugo_config['permalinks'] = {}
144 hugo_config['permalinks']['post'] = '/:filename/'
145 if 'name' in m['value']['content']:
146 hugo_config['title'] = m['value']['content']['name']
147 hugo_config['params'] = {}
148 if 'description' in m['value']['content']:
149 description = m['value']['content']['description']
150 hugo_config['params']['subtitle'] = description.replace('\n', ' ')
151 return (hugo_config)
152
153def write_hugo_config_from_user(ssb_userid):
154 metadata = get_user_metadata(ssb_userid)
155 for file in ['hugo/config.toml', 'hugo/config.yaml']:
156 if os.path.exists(file):
157 os.remove(file)
158 with open('hugo/config.json', 'w') as f:
159 f.write (json.dumps(build_hugo_config(metadata), indent = 4))
160
161def run_hugo():
162 subprocess.run(['hugo', '-s', 'hugo'])
163
164run_sbot()
165write_posts_from_user(conf.ssb_userid)
166write_hugo_config_from_user(conf.ssb_userid)
167check_hugo_theme(conf.hugo_theme, conf.hugo_theme_clone_url)
168run_hugo()
169
170

Built with git-ssb-web