-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathMobileBlogger.py
More file actions
193 lines (152 loc) · 5.3 KB
/
MobileBlogger.py
File metadata and controls
193 lines (152 loc) · 5.3 KB
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
# coding: utf-8
# http://codenugget.co/2015/11/18/mobile-blogging-with-pythonista-jekyll-and-github.html
# https://gist.github.com/b00giZm/cc704ba2a96e4a319e9e#file-mobileblogger-py
from __future__ import print_function
import appex
import console
import keychain
import dialogs
import re
from pygithub3 import Github
from string import Template
from datetime import date
from time import strftime
from unicodedata import normalize
def slug(text, encoding=None,
permitted_chars='abcdefghijklmnopqrstuvwxyz0123456789-'):
if isinstance(text, str):
text = text.decode(encoding or 'ascii')
clean_text = text.strip().replace(' ', '-').lower()
while '--' in clean_text:
clean_text = clean_text.replace('--', '-')
ascii_text = normalize('NFKD', clean_text).encode('ascii', 'ignore')
strict_text = map(lambda x: x if x in permitted_chars else '', ascii_text)
return ''.join(strict_text)
def extract_title(text):
lines = re.split('\n+', text, 2)
title = re.sub('^#+\s+', '', lines[0])
if (len(lines) < 2):
return (title, None)
index = 1
if re.search('^(=|-)+$', lines[1]):
index = 2
return (title, '\n'.join(lines[index:]))
class MobileBlogger:
def __init__(self, github_user, github_password, github_repo):
self.github_user = github_user
self.github_password = github_password
self.github_repo = github_repo
self._latest_commit = None
self._initialize_client()
def _initialize_client(self):
self._gh = Github(
login=self.github_user,
user=self.github_user,
password=self.github_password,
repo=self.github_repo
)
def _get_latest_commit(self, reload=False):
if self._latest_commit is None or reload:
self._latest_commit = self._gh.repos.commits.list().next().next()
return self._latest_commit
def _prepend_meta_data(self, text, metas):
template ='''---
layout: ${layout}
title: ${title}
author: ${author}
date: ${date}
tags: ${tags}
---
'''
return Template(template).substitute(metas) + text
def create_new_post(self, title, text, metas):
default_metas = {
'layout': 'post',
'date': strftime("%Y-%m-%d %H:%M:%S"),
'title': title
}
default_metas.update(metas)
branch = default_metas['branch']
filename = default_metas['filename']
del default_metas['branch']
del default_metas['filename']
text = self._prepend_meta_data(text, default_metas)
latest_commit = self._get_latest_commit()
# Create blob
blob = self._gh.git_data.blobs.create(dict(
content=text, encoding='utf-8'))
# Create tree
tree = self._gh.git_data.trees.create(dict(
base_tree=latest_commit.commit.tree['sha'], tree=[dict(
path='_posts/' + filename, mode='100644', type='blob', sha=blob.sha)]))
# Create commit
commit = self._gh.git_data.commits.create(dict(
message=('New post: ' + title), tree=tree.sha, parents=[
latest_commit.sha]))
#Update reference
ref = 'heads/%s' % branch
self._gh.git_data.references.update(ref, dict(
sha=commit.sha))
def undo_last_post(self, branch='main'):
if self._latest_commit is None:
return
ref = 'heads/%s' % branch
self._gh.git_data.references.update(ref, dict(
sha=self._latest_commit.sha, force=True))
def main():
if not appex.is_running_extension():
print('Running in Pythonista app, using test data...\n')
text = '''
'''
else:
text = appex.get_text()
if text:
author = 'Taha Dhiaeddine Amdouni'
github_repo = 'tdamdouni.github.io'
github_user = 'tdamdouni'
github_password = keychain.get_password('github', github_user) or ''
(title, text) = extract_title(text)
filename = '%s-%s.md' % (date.today(), slug(title))
github_fields = (
'Github Settings',
[
dict(title='Github Username', key='github_user', type='text', value=github_user, autocorrection=False, autocapitalization=False),
dict(title='Github Password', key='github_password', type='password', value=github_password),
dict(title='Repository', key='github_repo', type='text', value=github_repo, autocorrection=False, autocapitalization=False)
]
)
posting_fields = (
'Post Settings',
[
dict(title='Title', key='title', type='text', value=title),
dict(title='Author', key='author', type='text', value=author),
dict(title='Layout', key='layout', type='text', value='post', autocorrection=False, autocapitalization=False),
dict(title='Tags', key='tags', type='text', value=''),
dict(title='Filename', key='filename', type='text', value=filename, autocorrection=False, autocapitalization=False)
],
'Please seperate tags by spaces.'
)
results = dialogs.form_dialog(title='Publish new post', sections=[
posting_fields,
github_fields
])
if results is None:
console.hud_alert('Posting was cancelled', 'error')
return
metas = {
'tags': results['tags'],
'branch': 'main',
'author': results['author'],
'layout': results['layout'],
'filename': results['filename']
}
if github_password != results['github_password']:
keychain.set_password('github', results['github_user'], results['github_password'])
console.show_activity()
mb = MobileBlogger(results['github_user'], results['github_password'], results['github_repo'])
mb.create_new_post(results['title'], text, metas)
console.hud_alert('New post created!')
else:
print('No input text found.')
if __name__ == '__main__':
main()