convert.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # -*- coding: utf-8 -*-
  2. from .__load__ import *
  3. class Convert(object):
  4. def crearSignature(self):
  5. num = Demeter.time() - 3600*24
  6. model = Demeter.model('signature')
  7. model.cdate.assign(num, exp='<=')
  8. model.delete()
  9. def signature(self, site_id, appid, appsecret, timestamp, nonce, file, file_id, uid, status = 1):
  10. sign = Demeter.sha1(appid + '&' + appsecret + '&' + str(timestamp) + '&' + str(nonce) + '&' + file + '&' + str(file_id) + '&' + str(uid));
  11. time = Demeter.time()
  12. num = 3600*12
  13. if time - int(timestamp) > num:
  14. return False
  15. # sign 只能使用一次
  16. if status < 10:
  17. model = Demeter.model('signature')
  18. model.signature = sign
  19. model.site_id = site_id
  20. info = model.select(type='fetchone')
  21. if info:
  22. return False
  23. param = {}
  24. param['signature'] = sign
  25. param['appid'] = appid
  26. param['appsecret'] = appsecret
  27. param['timestamp'] = timestamp
  28. param['nonce'] = nonce
  29. param['file'] = file
  30. param['file_id'] = file_id
  31. param['uid'] = uid
  32. if status < 10:
  33. model.signature = sign
  34. model.site_id = site_id
  35. model.insert()
  36. return param
  37. def update(self, site, appid, file, file_id, file_type, uid):
  38. info = self.getFile(appid, file)
  39. convert = Demeter.model('convert')
  40. convert.site_id = site
  41. convert.key = info['key']
  42. data = convert.select(type='fetchone')
  43. if not data:
  44. convert.site_id = site
  45. convert.uid = uid
  46. convert.file_id = file_id
  47. convert.file_type = file_type
  48. convert.file_size = 0
  49. convert.file = info['file']
  50. convert.key = info['key']
  51. convert.name = info['name']
  52. convert.ext = info['ext']
  53. convert.local = info['local']
  54. convert.path = info['path']
  55. convert.pdf = info['pdf']
  56. convert.html = info['html']
  57. convert.url = info['url']
  58. id = convert.insert()
  59. info['status'] = 1
  60. info['id'] = id
  61. else:
  62. info['id'] = data['id']
  63. info['status'] = data['status']
  64. if uid:
  65. self.auth(site, uid, info['id'], 1)
  66. return info
  67. def getAuth(self, site, uid, convert_id):
  68. user = Demeter.model('user')
  69. user.uid = uid
  70. user.site_id = site
  71. user.convert_id = convert_id
  72. data = user.select(type='fetchone')
  73. return data
  74. def auth(self, site, uid, convert_id, status):
  75. user = Demeter.model('user')
  76. user.uid = uid
  77. user.site_id = site
  78. user.convert_id = convert_id
  79. data = user.select(type='fetchone')
  80. if not data:
  81. user.site_id = site
  82. user.uid = uid
  83. user.convert_id = convert_id
  84. user.status = status
  85. user.insert()
  86. elif data['status'] != status:
  87. # 适用于文档转让
  88. user.id = data['id']
  89. update = {}
  90. update['status'] = status
  91. user.update(update)
  92. return True
  93. def get(self, site, appid, file):
  94. convert = Demeter.model('convert')
  95. convert.site_id = site
  96. #convert.key = self.getKey(appid, file)
  97. convert.key = file
  98. data = convert.select(type='fetchone')
  99. return data
  100. def getKey(self, appid, file):
  101. return Demeter.sha1(str(appid) + '_' + str(file))
  102. def getFile(self, appid, file):
  103. info = {}
  104. (filepath,temp) = os.path.split(file)
  105. (filename,extension) = os.path.splitext(temp)
  106. info['file'] = file
  107. info['key'] = self.getKey(appid, file)
  108. info['ext'] = extension
  109. info['name'] = filename
  110. info = self.getLocalFile(appid, file, info)
  111. return info
  112. def getLocalFile(self, appid, file, info):
  113. day = str(date.today())
  114. day = day.split('-')
  115. #filename = Demeter.md5(str(uuid.uuid5(uuid.uuid1(), info['key'])))
  116. filename = info['key']
  117. filepath = str(appid) + '/' + day[0] + '/' + day[1] + '/' + day[2]
  118. path = ''
  119. if 'save' in Demeter.config['setting']:
  120. filepath = File.mkdirs(os.path.join(Demeter.config['setting']['save'], filepath)) + '/' + filename
  121. else:
  122. filepath = File.mkdirs(os.path.join(Demeter.path, 'runtime','files', filepath)) + '/' + filename
  123. local = filepath + info['ext']
  124. info['local'] = local
  125. info['pdf'] = filepath + '/' + filename + '.pdf'
  126. # 这里要增加权限控制 html不能直接访问
  127. info['html'] = filepath + '/' + filename + '.html'
  128. info['url'] = info['html'].replace(Demeter.path + 'runtime', '')
  129. info['path'] = filepath + '/'
  130. return info
  131. if File.exists(local):
  132. return info
  133. else:
  134. self.download(file, local);
  135. return info
  136. def download(self, file, local):
  137. if 'http' in file:
  138. import requests
  139. r = requests.get(file, stream=True)
  140. with open(local, 'wb') as up:
  141. for chunk in r.iter_content(chunk_size=1024):
  142. if chunk:
  143. up.write(chunk)
  144. else:
  145. import shutil
  146. shutil.copyfile(file, local)
  147. if File.exists(local):
  148. return True
  149. return False
  150. def command(self, info):
  151. File.mkdir(info['path'])
  152. convert = 'cd ' + info['path'] + ' && '
  153. if info['ext'] != '.pdf':
  154. convert = convert + 'libreoffice --invisible --convert-to pdf ' + info['local']
  155. convert = convert + ' && '
  156. else:
  157. info['pdf'] = info['local']
  158. convert = convert + 'pdf2htmlEX --zoom 1.5 --use-cropbox 0 --no-drm 1 --split-pages 1 '
  159. convert = convert + '--embed-css 0 --embed-javascript 0 --embed-image 0 --embed-font 1 --process-outline 0 '
  160. convert = convert + '--embed-external-font 0 --dest-dir '+info['path']+' --page-filename %d.page ' + info['pdf']
  161. return convert
  162. def total(self, path):
  163. page = 0
  164. for parentdir,dirname,filenames in os.walk(path):
  165. for filename in filenames:
  166. if os.path.splitext(filename)[1]=='.page':
  167. page = page + 1
  168. return page
  169. def handle(self, id):
  170. model = Demeter.model('convert')
  171. model.id = id
  172. info = model.select(type='fetchone')
  173. if not info:
  174. return
  175. siteModel = Demeter.model('site')
  176. siteModel.id = info['site_id']
  177. site = siteModel.select(type='fetchone')
  178. status = True
  179. if info['status'] == 1 or info['status'] == 4:
  180. status = False
  181. if info and status == False:
  182. model.id = id
  183. update = {}
  184. update['status'] = 2
  185. model.update(update)
  186. if not File.exists(info['local']):
  187. self.download(info['file'], info['local'])
  188. if not File.exists(info['html']):
  189. #if info:
  190. handle = self.command(info)
  191. Shell.popen(handle)
  192. if File.exists(info['html']):
  193. # 截屏
  194. self.cut(info)
  195. #self.string_switch(info['html'], "taste", "tasting")
  196. # 获取有多少页
  197. page = self.total(info['path'])
  198. model.id = id
  199. size = os.path.getsize(info['local'])
  200. update = {}
  201. update['file_size'] = size
  202. update['page'] = page
  203. update['status'] = 3
  204. model.update(update)
  205. # 通知接口 通知应用成功转换
  206. info['page'] = page
  207. info['file_size'] = size
  208. self.api(info, site)
  209. return
  210. model.id = id
  211. update = {}
  212. update['status'] = 4
  213. model.update(update)
  214. def api(self, info, site):
  215. if 'file_id' in info and info['file_id']:
  216. api = site['api']
  217. appid = site['appid']
  218. appsecret = site['appsecret']
  219. timestamp = Demeter.time()
  220. nonce = Demeter.hash()
  221. file = info['key']
  222. file_id = info['file_id']
  223. uid = info['uid']
  224. param = self.signature(site['id'], appid, appsecret, timestamp, nonce, file, file_id, uid)
  225. param['url'] = 'main/view'
  226. param['img'] = info['url'] + '.jpg'
  227. param['page'] = info['page']
  228. param['ext'] = info['ext']
  229. param['file_size'] = info['file_size']
  230. Demeter.curl(api, param, 'post')
  231. def cut(self, info):
  232. from wand.image import Image
  233. pdf = Image(filename=info['pdf'], resolution=50)
  234. jpg = pdf.convert('jpg')
  235. req_image = []
  236. i = 0
  237. for img in jpg.sequence:
  238. if i == 0:
  239. img_page = Image(image=img)
  240. req_image.append(img_page.make_blob('jpg'))
  241. i = i+1
  242. dest = info['html']
  243. for img in req_image:
  244. ff = open(dest + '.jpg','wb')
  245. ff.write(img)
  246. ff.close()
  247. def string_switch(self, x,y,z,s=1):
  248. with open(x, "r", encoding="utf-8") as f:
  249. #readlines以列表的形式将文件读出
  250. lines = f.readlines()
  251. with open(x, "w", encoding="utf-8") as f_w:
  252. #定义一个数字,用来记录在读取文件时在列表中的位置
  253. n = 0
  254. #默认选项,只替换第一次匹配到的行中的字符串
  255. if s == 1:
  256. for line in lines:
  257. if y in line:
  258. line = line.replace(y,z)
  259. f_w.write(line)
  260. n += 1
  261. break
  262. f_w.write(line)
  263. n += 1
  264. #将剩余的文本内容继续输出
  265. for i in range(n,len(lines)):
  266. f_w.write(lines[i])
  267. #全局匹配替换
  268. elif s == 'g':
  269. for line in lines:
  270. if y in line:
  271. line = line.replace(y,z)
  272. f_w.write(line)