forked from ynhacler/RedKindle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pushworker.py
408 lines (343 loc) · 10.3 KB
/
pushworker.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
#-*- coding:utf-8 -*-
import os,re,urllib,urlparse,datetime,logging
from datetime import date, timedelta
from books.base import BaseFeedBook, BaseUrlBook,WebpageBook
from jinja2 import Environment, PackageLoader
from os import path, listdir, system
from shutil import copy,copytree,rmtree
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import mimetypes
from random import randrange
import model
import time
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
#动态载入手工处理的feeds
from books import FeedClasses, FeedClass
from config import *
#生产模板
def render_and_write(template_name, context, output_name, output_dir,templates_env):
"""Render `template_name` with `context` and write the result in the file
`output_dir`/`output_name`."""
template = templates_env.get_template(template_name)
f = open(path.join(output_dir, output_name), "w")
f.write(template.render(**context).encode('utf-8'))
f.close()
#生产mobi
def mobi(input_file, exec_path,logging=None):
"""Execute the KindleGen binary to create a MOBI file."""
try:
logging.info("generate .mobi file start... ")
system("%s %s" % (exec_path, input_file))
return 'metadata.mobi'
except Exception, e:
logging.error("Error: %s" % e)
return ''
#epub
def epub(r_path,t_path,e_path, logging=None):
try:
os.chdir(path.join(r_path,t_path,e_path))
logging.info("generate .epub file start... ")
system("zip -X -9 -r book1.epub.zip * -x mimetype")
system("zip -X -0 book1.epub.zip mimetype")
system("mv book1.epub.zip daily.epub")
os.chdir(r_path)
return 'daily.epub'
except Exception, e:
logging.error("Error: %s" % e)
return ''
#发邮件
def send_mail(from_addr,to_addr,attach_path,ifmobi,logging=None):
try:
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'Redkindle'
msg.attach(MIMEText(''))
ctype, encoding = mimetypes.guess_type(attach_path)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
part = MIMEBase(maintype, subtype)
with open(attach_path, 'rb') as fp:
part.set_payload(fp.read())
encoders.encode_base64(part)
if ifmobi == 1:
filename=ATTACH_FILENAME+".mobi"
else:
filename=ATTACH_FILENAME+".epub"
part.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(part)
smtp = smtplib.SMTP('127.0.0.1', 25)
smtp.sendmail(from_addr, to_addr, msg.as_string())
smtp.quit()
except Exception, e:
logging.error("fail:%s" % e)
#抓文章存在mysql
def pushwork2(f_id,feeds):
#区别是自动还是手动处理的
log = logging.getLogger()
#自动
if cmp('http',feeds[0][1][0:4].lower()) == 0:
redbook = BaseFeedBook(log)
redbook.feeds = feeds
else:
#手动
mfeedclasses = FeedClasses()
for mfeed in mfeedclasses:
for my_mfeed in feeds:
if mfeed.__name__ == my_mfeed[1]:
redbook = mfeed(log)
ROOT = path.dirname(path.abspath(__file__))
temp_dir = path.join(ROOT, 'temp')
#创建文件夹
output_dir = path.join(temp_dir,'feed_%s' % f_id)
isExists = path.exists(output_dir)
if isExists:
rmtree(output_dir)
time.sleep(3)
isExists = path.exists(output_dir)
if not isExists:
os.makedirs(output_dir)
print 'mkdir'
time.sleep(1)
#清空对应的mysql表
model.delete_old_article(f_id)
time.sleep(0.5)
for sec_or_media, url, title, content,brief in redbook.Items():
if sec_or_media.startswith(r'image/'):
filename = path.join(output_dir,title)
fout = open(filename, "wb")
fout.write(content)
fout.close()
else:
model.put_section_article(f_id,sec_or_media, url, title, content,brief)
#改变更新时间
model.update_article_update_time(f_id)
print '-=end grasp=-'
#worker生产电子书,并推送
def pushwork(email,feeds,mfeeds,ifimg):
# log = default_log
log = logging.getLogger()
#放所有的feeds(手工和自动处理的)
feedsclasses = []
#得到出手工处理的feed目录
mfeedclasses = FeedClasses()
for mfeed in mfeedclasses:
for my_mfeed in mfeeds:
print mfeed.__name__
print my_mfeed[0]
print '-=-=-=-=-=-=-=-'
if mfeed.__name__ == my_mfeed[0]:
temp_mfeed = mfeed(log)
feedsclasses.append(temp_mfeed)
#自动处理的
redbook = BaseFeedBook(log)
redbook.feeds = feeds
feedsclasses.append(redbook)
#是否要图片
if ifimg == 0:
for feed in feedsclasses:
feed.keep_image = False
#所有的信息
sum_pic_size = 0#getsize('test.png')/1024 MAX_PIC_SIZE
data = []
feed_number = 1
entry_number = 0
play_order = 0
#总的img计数
imgindex_temp = 0
temp_sec = ''
ROOT = path.dirname(path.abspath(__file__))
output_dir = path.join(ROOT, 'temp')
templates_env = Environment(loader=PackageLoader('bmaintest', 'templates2'))
img_num = []
i=-1 #对feed进行计数
for feed in feedsclasses:
print feed.__class__.__name__
print '--------'
feed._imgindex = imgindex_temp
for sec_or_media, url, title, content,brief in feed.Items():
if sec_or_media.startswith(r'image/'):
if sum_pic_size < MAX_PIC_SIZE:
filename = path.join(ROOT, 'temp',title)
img_num.append(title)
fout = open(filename, "wb")
fout.write(content)
fout.close()
sum_pic_size += path.getsize(filename)/1024
else:
#新的feed开始
if temp_sec != sec_or_media:
temp_sec = sec_or_media
feed_number += 1
play_order += 1
entry_number = 0
local = {
'number':feed_number,
'play_order':play_order,
'entries':[],
'title':sec_or_media
}
i += 1
data.insert(i,local)
#处理文章
play_order += 1
entry_number += 1
local_entry = {
'number':entry_number,
'play_order':play_order,
'title':title,
'description':brief,
'content':content,
'url':url,
}
data[i]['entries'].append(local_entry)
imgindex_temp = feed._imgindex
#=====================end for
wrap ={
'date': date.today().isoformat(),
'feeds':data,
'img_nums':imgindex_temp,
'img_name':img_num,
}
## TOC (NCX)
render_and_write('toc.xml', wrap, 'toc.ncx', output_dir,templates_env)
## COVER (HTML)
render_and_write('cover.html',wrap,'cover.html',output_dir,templates_env)
## TOC (HTML)
render_and_write('toc.html', wrap, 'toc.html', output_dir,templates_env)
## OPF
render_and_write('opf.xml', wrap, 'daily.opf', output_dir,templates_env)
#/home/zzh/Desktop/temp/v3
for feed in data:
for entry in feed['entries']:
render_and_write('feed.html',entry,'article_%s_%s.html' % (feed['number'],entry['number']),output_dir,templates_env)
#copy cover.jpg
copy(path.join(ROOT, 'templates2', 'masthead.jpg'), path.join(output_dir, 'masthead.jpg'))
copy(path.join(ROOT, 'templates2', 'cover.jpg'), path.join(output_dir, 'cover.jpg'))
#gen mobi
mobi_file = mobi(path.join(output_dir,'daily.opf'),path.join(ROOT,'kindlegen_1.1') ,log)
#send mail
if mobi_file :
mobi_file = path.join(output_dir,mobi_file)
#fp = open(mobi_file, 'rb')
# sendmail(fp.read())
# fp.close()
send_mail(SrcEmail,email,mobi_file,log)
#clean
for fn in listdir(output_dir):
f_path = path.join(output_dir, fn)
if path.isfile( f_path):
os.remove(f_path)
return '-=end=-'
#从mysql中提取数据
def pushwork3(email,feeds,ifimg,ifmobi):#feeds只存有编号,ifmobi=1
#相关信息
log = logging.getLogger()
sum_pic_size = 0#getsize('test.png')/1024 MAX_PIC_SIZE
data = []
feed_number = 1
entry_number = 0
play_order = 0
#总的img计数
imgindex_temp = 0
temp_sec = ''
ROOT = path.dirname(path.abspath(__file__))
if ifmobi == 1:
output_dir = path.join(ROOT, 'temp','mobi')
else:
output_dir = path.join(ROOT, 'temp','epub','OEBPS')
templates_env = Environment(loader=PackageLoader('bmaintest', 'templates2'))
img_num = []
i=-1 #对feed进行计数
for feed in feeds:
#从mysql中读取
temp_article = model.get_article2id(feed)
if len(temp_article) == 0:
continue
feed_number +=1
play_order += 1
entry_number = 0
local = {
'number':feed_number,
'play_order':play_order,
'entries':[],
'title':''
}
i += 1
data.insert(i,local)
for article in temp_article:
play_order += 1
entry_number += 1
local_entry = {
'number':entry_number,
'play_order':play_order,
'title':article['title'],
'description':article['brief'],
'content':article['content'],
'url':article['url'],
}
data[i]['entries'].append(local_entry)
data[i]['title'] = article['section']
#图片
if ifimg == 1:
img_dir = path.join(ROOT,'temp','feed_%s' % feed)
for fn in listdir(img_dir):
if sum_pic_size < MAX_PIC_SIZE:
f_path = path.join(img_dir, fn)
sum_pic_size += path.getsize(f_path)/1024
img_num.append(fn)
copy(f_path, path.join(output_dir, fn))
imgindex_temp += 1
else:
imgindex_temp = 0
img_num = []
#==============================end for
wrap ={
'date': date.today().isoformat(),
'feeds':data,
'img_nums':imgindex_temp,
'img_name':img_num,
}
## TOC (NCX)
render_and_write('toc.xml', wrap, 'toc.ncx', output_dir,templates_env)
## COVER (HTML)
render_and_write('cover.html',wrap,'cover.html',output_dir,templates_env)
## TOC (HTML)
render_and_write('toc.html', wrap, 'toc.html', output_dir,templates_env)
## OPF
render_and_write('opf.xml', wrap, 'metadata.opf', output_dir,templates_env)
#/home/zzh/Desktop/temp/v3
for feed in data:
for entry in feed['entries']:
render_and_write('feed.html',entry,'article_%s_%s.html' % (feed['number'],entry['number']),output_dir,templates_env)
#copy cover.jpg
copy(path.join(ROOT, 'templates2', 'masthead.jpg'), path.join(output_dir, 'masthead.jpg'))
copy(path.join(ROOT, 'templates2', 'cover.jpg'), path.join(output_dir, 'cover.jpg'))
#gen mobi
if ifmobi == 1:
mobi_file = mobi(path.join(output_dir,'metadata.opf'),path.join(ROOT,'kindlegen_1.1') ,log)
if mobi_file :
mobi_file = path.join(output_dir,mobi_file)
send_mail(SrcEmail,email,mobi_file,1,log)
else:
epub_file = epub(ROOT,'temp','epub',log)
if epub_file:
epub_file = path.join(ROOT,'temp','epub',epub_file)
send_mail(SrcEmail,email,epub_file,0,log)
if path.isfile( epub_file):
os.remove(epub_file)
#clean
for fn in listdir(output_dir):
f_path = path.join(output_dir, fn)
if path.isfile( f_path):
os.remove(f_path)
return '-=end=-'
if __name__=="__main__":
pushwork3('aaaa',[16],0,1)