convert.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. filepath = File.mkdirs(os.path.join(Demeter.path, 'runtime','files', filepath)) + '/' + filename
  119. local = filepath + info['ext']
  120. info['local'] = local
  121. info['pdf'] = filepath + '/' + filename + '.pdf'
  122. # 这里要增加权限控制 html不能直接访问
  123. info['html'] = filepath + '/' + filename + '.html'
  124. info['url'] = info['html'].replace(Demeter.path + 'runtime', '')
  125. info['path'] = filepath + '/'
  126. return info
  127. if File.exists(local):
  128. return info
  129. else:
  130. self.download(file, local);
  131. return info
  132. def download(self, file, local):
  133. if 'http' in file:
  134. import requests
  135. r = requests.get(file, stream=True)
  136. with open(local, 'wb') as up:
  137. for chunk in r.iter_content(chunk_size=1024):
  138. if chunk:
  139. up.write(chunk)
  140. else:
  141. import shutil
  142. shutil.copyfile(file, local)
  143. if File.exists(local):
  144. return True
  145. return False
  146. def command(self, info):
  147. File.mkdir(info['path'])
  148. convert = 'cd ' + info['path'] + ' && '
  149. if info['ext'] != '.pdf':
  150. convert = convert + 'libreoffice --invisible --convert-to pdf ' + info['local']
  151. convert = convert + ' && '
  152. else:
  153. info['pdf'] = info['local']
  154. convert = convert + 'pdf2htmlEX --zoom 1.5 --no-drm 1 --split-pages 1 '
  155. convert = convert + '--embed-css 0 --embed-javascript 0 --embed-image 0 --embed-font 1 --process-outline 0 '
  156. convert = convert + '--embed-external-font 0 --dest-dir '+info['path']+' --page-filename %d.page ' + info['pdf']
  157. return convert
  158. def total(self, path):
  159. page = 0
  160. for parentdir,dirname,filenames in os.walk(path):
  161. for filename in filenames:
  162. if os.path.splitext(filename)[1]=='.page':
  163. page = page + 1
  164. return page
  165. def handle(self, id):
  166. model = Demeter.model('convert')
  167. model.id = id
  168. info = model.select(type='fetchone')
  169. if not info:
  170. return
  171. siteModel = Demeter.model('site')
  172. siteModel.id = info['site_id']
  173. site = siteModel.select(type='fetchone')
  174. status = True
  175. if info['status'] == 1 or info['status'] == 4:
  176. status = False
  177. if info and status == False:
  178. model.id = id
  179. update = {}
  180. update['status'] = 2
  181. model.update(update)
  182. if not File.exists(info['local']):
  183. self.download(info['file'], info['local'])
  184. if not File.exists(info['html']):
  185. #if info:
  186. handle = self.command(info)
  187. Shell.popen(handle)
  188. if File.exists(info['html']):
  189. # 截屏
  190. self.cut(info)
  191. #self.string_switch(info['html'], "taste", "tasting")
  192. # 获取有多少页
  193. page = self.total(info['path'])
  194. model.id = id
  195. size = os.path.getsize(info['local'])
  196. update = {}
  197. update['file_size'] = size
  198. update['page'] = page
  199. update['status'] = 3
  200. model.update(update)
  201. # 通知接口 通知应用成功转换
  202. info['page'] = page
  203. info['file_size'] = size
  204. self.api(info, site)
  205. return
  206. model.id = id
  207. update = {}
  208. update['status'] = 4
  209. model.update(update)
  210. def api(self, info, site):
  211. if 'file_id' in info and info['file_id']:
  212. api = site['api']
  213. appid = site['appid']
  214. appsecret = site['appsecret']
  215. timestamp = Demeter.time()
  216. nonce = Demeter.hash()
  217. file = info['key']
  218. file_id = info['file_id']
  219. uid = info['uid']
  220. param = self.signature(site['id'], appid, appsecret, timestamp, nonce, file, file_id, uid)
  221. param['url'] = 'main/view'
  222. param['img'] = info['url'] + '.jpg'
  223. param['page'] = info['page']
  224. param['ext'] = info['ext']
  225. param['file_size'] = info['file_size']
  226. Demeter.curl(api, param, 'post')
  227. def cut(self, info):
  228. from wand.image import Image
  229. pdf = Image(filename=info['pdf'], resolution=50)
  230. jpg = pdf.convert('jpg')
  231. req_image = []
  232. i = 0
  233. for img in jpg.sequence:
  234. if i == 0:
  235. img_page = Image(image=img)
  236. req_image.append(img_page.make_blob('jpg'))
  237. i = i+1
  238. dest = info['html']
  239. for img in req_image:
  240. ff = open(dest + '.jpg','wb')
  241. ff.write(img)
  242. ff.close()
  243. def string_switch(self, x,y,z,s=1):
  244. with open(x, "r", encoding="utf-8") as f:
  245. #readlines以列表的形式将文件读出
  246. lines = f.readlines()
  247. with open(x, "w", encoding="utf-8") as f_w:
  248. #定义一个数字,用来记录在读取文件时在列表中的位置
  249. n = 0
  250. #默认选项,只替换第一次匹配到的行中的字符串
  251. if s == 1:
  252. for line in lines:
  253. if y in line:
  254. line = line.replace(y,z)
  255. f_w.write(line)
  256. n += 1
  257. break
  258. f_w.write(line)
  259. n += 1
  260. #将剩余的文本内容继续输出
  261. for i in range(n,len(lines)):
  262. f_w.write(lines[i])
  263. #全局匹配替换
  264. elif s == 'g':
  265. for line in lines:
  266. if y in line:
  267. line = line.replace(y,z)
  268. f_w.write(line)