forked from ajdavis/motor-blog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
256 lines (207 loc) · 8.04 KB
/
models.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
import datetime
from bson.objectid import ObjectId
from dictshield.document import Document, EmbeddedDocument
from dictshield.fields import StringField, IntField, DateTimeField
from dictshield.fields.compound import SortedListField, EmbeddedDocumentField, ListField
from dictshield.fields.mongo import ObjectIdField
from motor_blog.text.link import absolute
import pytz
from motor_blog.text import markup, summarize, slugify, plain
utc_tz = pytz.timezone('UTC')
class BlogDocument(Document):
@property
def date_created(self):
"""datetime when this post was created, timezone-aware in UTC"""
return self.id.generation_time
class Meta:
id_field = ObjectIdField
class Category(BlogDocument):
name = StringField()
slug = StringField()
@classmethod
def _from_rpc(cls, struct, name):
_id = ObjectId(
struct['categoryId']) if 'categoryId' in struct else None
return cls(name=name, slug=slugify.slugify(name), id=_id)
@classmethod
def from_wordpress(cls, struct):
name = struct['name']
return cls._from_rpc(struct, name)
@classmethod
def from_metaweblog(cls, struct):
name = struct['categoryName']
return cls._from_rpc(struct, name)
def to_wordpress(self, application):
url = absolute(application.reverse_url('category', self.slug))
return {
'categoryId': str(self.id),
'categoryName': self.name,
'htmlUrl': url,
'rssUrl': url,
}
to_metaweblog = to_wordpress
@property
def last_modified(self):
return self.date_created
class EmbeddedCategory(Category, EmbeddedDocument):
pass
class GuestAccessToken(EmbeddedDocument):
"""One who knows the guest access token can see the unpublished draft."""
name = StringField()
token = ObjectIdField(auto_fill=True)
class Post(BlogDocument):
"""A post or a page"""
title = StringField(default='')
# Formatted for display.
body = StringField(default='')
# Input from MarsEdit or migrate_from_wordpress.
original = StringField(default='')
# Plain text.
plain = StringField(default='')
# Plain-text excerpt.
summary = StringField(default='')
author = StringField(default='')
type = StringField(choices=('post', 'page'), default='post')
status = StringField(
choices=('publish', 'draft', 'redirect'), default='publish')
meta_description = StringField(default='')
tags = SortedListField(StringField())
categories = SortedListField(EmbeddedDocumentField(EmbeddedCategory))
slug = StringField(default='')
guest_access_tokens = ListField(EmbeddedDocumentField(GuestAccessToken))
wordpress_id = IntField() # legacy id from WordPress
pub_date = DateTimeField()
mod = DateTimeField()
# Post was moved, this is its new slug.
redirect = StringField(default=None)
def __init__(self, *args, **kwargs):
super(Post, self).__init__(*args, **kwargs)
if not self.mod.tzinfo:
self.mod = utc_tz.localize(self.mod)
@classmethod
def from_metaweblog(
cls, struct, post_type='post', is_edit=False
):
"""Receive metaWeblog RPC struct and initialize a Post.
Used both by migrate_from_wordpress and when receiving a new or
edited post from MarsEdit.
"""
title = struct.get('title', '')
meta_description = struct.get('mt_excerpt', '')
if len(meta_description) > 155:
raise ValueError(
"Description is %d chars, max 155" % len(meta_description))
if 'mt_keywords' in struct:
tags = [
tag.strip() for tag in struct['mt_keywords'].split(',')
if tag.strip()
]
else:
tags = None
slug = (
slugify.slugify(struct['wp_slug'])
if struct.get('wp_slug')
else slugify.slugify(title))
description = struct.get('description', '')
status = struct.get('post_status', 'publish')
if 'date_modified_gmt' in struct:
tup = struct['date_modified_gmt'].timetuple()
mod = utc_tz.localize(datetime.datetime(*tup[0:6]))
else:
mod = datetime.datetime.utcnow()
body = markup.markup(description)
rv = cls(
title=title,
# Format for display
body=body,
plain=plain.plain(body),
summary=summarize.summarize(body, 200),
original=description,
meta_description=meta_description,
tags=tags,
slug=slug,
type=post_type,
status=status,
wordpress_id=struct.get('postid'),
mod=mod
)
if not is_edit and 'date_created_gmt' in struct:
# TODO: can fail if two posts created in same second, add random
# suffix to ObjectId
date_created = datetime.datetime.strptime(
struct['date_created_gmt'].value, "%Y%m%dT%H:%M:%S")
rv.id = ObjectId.from_datetime(date_created)
return rv
def to_metaweblog(self, application):
# We're kind of throwing fieldnames at the wall and seeing what sticks,
# MarsEdit expects different names in the responses to different API
# calls.
if self.status == 'publish':
url = absolute(application.reverse_url('post', self.slug))
else:
url = absolute(application.reverse_url('draft', self.slug))
rv = {
'title': self.title,
# Note we're returning the original, not the display version
'description': self.original,
'link': url,
'permaLink': url,
'categories': [
cat.to_metaweblog(application) for cat in self['categories']],
'mt_keywords': ','.join(self['tags']),
'dateCreated': self.local_date_created(application),
'date_created_gmt': self.date_created,
'postid': str(self.id),
'id': str(self.id),
'status': self.status,
'wp_slug': self.slug,
'mt_excerpt': self.meta_description,
}
if self.type == 'post':
rv['post_id'] = str(self.id)
rv['post_status'] = self.status
elif self.type == 'page':
rv['page_id'] = str(self.id)
rv['page_status'] = self.status
return rv
def to_python(self):
dct = super(Post, self).to_python()
# Avoid bug where metaWeblog_editPost() sets categories to []
if not self.categories:
dct.pop('categories', None)
# TODO: for other models, too?
if 'id' in dct:
dct['_id'] = dct.pop('id')
return dct
@property
def date_created(self):
if self.pub_date:
return utc_tz.localize(self.pub_date)
else:
return super(Post, self).date_created
def local_date_created(self, application):
dc = self.date_created
tz = application.settings['tz']
return tz.normalize(dc.astimezone(tz))
def local_short_date(self, application):
dc = self.local_date_created(application)
return '%s/%s/%s' % (dc.month, dc.day, dc.year)
def local_long_date(self, application):
dc = self.local_date_created(application)
return '%s %s, %s' % (dc.strftime('%b'), dc.day, dc.year)
def local_time_of_day(self, application):
dc = self.local_date_created(application)
return '%d:%02d %s' % (dc.hour % 12, dc.minute, dc.strftime('%p'))
@property
def last_modified(self):
return max(self.date_created, self.mod)
@property
def display_summary(self):
return self.meta_description if self.meta_description else self.summary
def has_guest_access_token(self, token):
"""Is the given ObjectId a valid access token?"""
assert isinstance(token, ObjectId)
for token_object in self.guest_access_tokens:
if token_object.token == token:
return True
return False