-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wordpress.py
309 lines (247 loc) · 8.95 KB
/
Wordpress.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-08-21 00:16:38
# @Author : Tom Hu ([email protected])
# @Link : http://h1994st.com
# @Version : 1.0
import json
import time
import dateutil.parser
from pprint import pprint
from urllib import urlencode
import httplib2
import Config
from auto_flow_leaker.auto_flow.post import Post
from auto_flow_leaker.auto_flow.channel import Channel
TIMEOUT = int(Config.Global('timeout'))
class Wordpress(Channel):
"""
Default user: covertsan ([email protected])
Common fields: ID, date, status, title, content
"""
def __init__(self):
super(Wordpress, self).__init__()
def _api_url(self, path):
API_BASE_URL = 'https://public-api.wordpress.com/rest/v1.1'
return API_BASE_URL + path
def description(self):
return 'site={!r}, access_token={!r}'.format(
Config.Wordpress('site'), Config.Wordpress('access_token'))
def send(self, content, title=None, **kwargs):
'''
Default title: unix epoch
'''
try:
post = self.create_post(
(title or '%.6f' % time.time()), content,
fields='ID,title,date', **kwargs)
except Exception as e:
print 'Wordpress send error:', e
return None
else:
return Post(
id=post['ID'],
title=post['title'],
create_time=dateutil.parser.parse(post['date']))
def receive_all(self, **kwargs):
def converter(post):
return Post(
id=post['ID'],
title=post['title'],
content=post['content'],
create_time=dateutil.parser.parse(post['date']))
return map(converter, self.get_posts(
fields='ID,title,date,content', **kwargs))
def delete(self, item):
self.delete_post(item.id)
def delete_all(self, permanent=True, category=None, tag=None):
self.delete_all_posts(
permanent=permanent, category=category, tag=tag)
@property
def posts(self):
return self.get_posts(fields='ID,title')
# Write
def create_post(self, title, body, fields=None,
categories=None, tags=None):
'''
POST /sites/$site/posts/new
'''
assert isinstance(title, (str, unicode)), title
assert isinstance(body, (str, unicode)), body
assert fields is None or isinstance(fields, (str, unicode)), fields
assert (categories is None or
isinstance(categories, (str, unicode))), categories
assert (tags is None or
isinstance(tags, (str, unicode))), tags
h = httplib2.Http(timeout=TIMEOUT)
post_data = {
'title': title,
'content': body
}
if categories is not None:
post_data['categories'] = categories
if tags is not None:
post_data['tags'] = tags
headers = {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Authorization': '%s %s' % (
Config.Wordpress('token_type'),
Config.Wordpress('access_token'))
}
parameters = dict()
if fields is not None:
parameters['fields'] = fields
(res_headers, content) = h.request(
self._api_url('/sites/%s/posts/new/?%s' % (
Config.Wordpress('site'), urlencode(parameters))),
method='POST',
headers=headers,
body=urlencode(post_data))
if res_headers.status / 100 != 2:
raise Exception((res_headers, content))
res = json.loads(content)
return res
def get_posts(self, number=100, fields=None,
category=None, tag=None, status='publish'):
'''
GET /sites/:site/posts/
'''
assert (number is not None and
isinstance(number, int) and
number <= 100 and number >= 1), number
assert fields is None or isinstance(fields, (str, unicode)), fields
assert (status is not None and
isinstance(status, (str, unicode))), status
assert status in [
'publish', 'private', 'draft',
'pending', 'future', 'trash',
'any'], status
assert (category is None or
isinstance(category, (str, unicode))), category
assert (tag is None or
isinstance(tag, (str, unicode))), tag
h = httplib2.Http(timeout=TIMEOUT)
headers = {
'Authorization': '%s %s' % (
Config.Wordpress('token_type'),
Config.Wordpress('access_token'))
}
parameters = {
'number': number,
'status': status
}
if fields is not None:
parameters['fields'] = fields
if category is not None:
parameters['category'] = category
if tag is not None:
parameters['tag'] = tag
(res_headers, content) = h.request(
self._api_url('/sites/%s/posts/?%s' % (
Config.Wordpress('site'), urlencode(parameters))),
method='GET',
headers=headers)
if res_headers.status / 100 != 2:
raise Exception((res_headers, content))
res = json.loads(content)
return res['posts']
# Read
def get_post(self, id, fields=None):
'''
GET /sites/:site/posts/:post_ID
'''
assert isinstance(id, int) and id >= 1, id
assert fields is None or isinstance(fields, (str, unicode)), fields
h = httplib2.Http(timeout=TIMEOUT)
headers = {
'Authorization': '%s %s' % (
Config.Wordpress('token_type'),
Config.Wordpress('access_token'))
}
parameters = dict()
if fields is not None:
parameters['fields'] = fields
(res_headers, content) = h.request(
self._api_url('/sites/%s/posts/%d/?%s' % (
Config.Wordpress('site'), id, urlencode(parameters))),
method='GET',
headers=headers)
if res_headers.status / 100 != 2:
raise Exception((res_headers, content))
res = json.loads(content)
return res
# Delete
def delete_post(self, id, fields=None):
'''
POST /sites/:site/posts/:post_ID/delete
'''
assert isinstance(id, int) and id >= 1, id
assert fields is None or isinstance(fields, (str, unicode)), fields
h = httplib2.Http(timeout=TIMEOUT)
headers = {
'Authorization': '%s %s' % (
Config.Wordpress('token_type'),
Config.Wordpress('access_token'))
}
parameters = dict()
if fields is not None:
parameters['fields'] = fields
(res_headers, content) = h.request(
self._api_url('/sites/%s/posts/%d/delete/?%s' % (
Config.Wordpress('site'), id, urlencode(parameters))),
method='POST',
headers=headers)
if res_headers.status / 100 != 2:
raise Exception((res_headers, content))
res = json.loads(content)
return res
def delete_all_posts(self, permanent=True, category=None, tag=None):
'''
Delete all the posts
'''
posts = self.get_posts(
fields='ID,status', status='publish',
category=category, tag=tag)
while len(posts) > 0:
for post in posts:
print 'Delete %d (%s)' % (post['ID'], post['status'])
try:
self.delete_post(post['ID'])
except Exception as e:
print ' Error:', e
posts = self.get_posts(
fields='ID,status', status='publish',
category=category, tag=tag)
if permanent:
posts = self.get_posts(
fields='ID,status', status='trash',
category=category, tag=tag)
while len(posts) > 0:
for post in posts:
print 'Delete %d (%s)' % (post['ID'], post['status'])
try:
self.delete_post(post['ID'])
except Exception as e:
print ' Error:', e
posts = self.get_posts(
fields='ID,status', status='publish',
category=category, tag=tag)
def test_wordpress():
w = Wordpress()
print w
# Read all
pprint(w.receive_all())
print 'Input file: ./data/eva_time_data_2.in'
with open('data/eva_time_data_2.in', 'r') as fp:
content = fp.read()
print w.send(content, categories='test', tags='tag_tata')
time.sleep(3)
pprint(w.receive_all())
# Delete all
w.delete_all()
# Read all
pprint(w.receive_all())
def force_delete():
Wordpress().delete_all()
if __name__ == '__main__':
force_delete()