convert.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 + 'soffice --headless --invisible --convert-to pdf ' + info['local']
  156. convert = convert + ' && '
  157. else:
  158. info['pdf'] = info['local']
  159. convert = convert + 'pdf2htmlEX --zoom 1 --use-cropbox 0 --no-drm 1 --split-pages 1 '
  160. convert = convert + '--embed-css 0 --embed-javascript 0 --embed-image 0 --embed-font 1 --process-outline 0 '
  161. convert = convert + '--embed-external-font 0 --dest-dir '+info['path']+' --page-filename %d.page ' + info['pdf']
  162. return convert
  163. def total(self, path):
  164. page = 0
  165. for parentdir,dirname,filenames in os.walk(path):
  166. for filename in filenames:
  167. if os.path.splitext(filename)[1]=='.page':
  168. page = page + 1
  169. return page
  170. def handle(self, id):
  171. model = Demeter.model('convert')
  172. model.id = id
  173. info = model.select(type='fetchone')
  174. if not info:
  175. return
  176. siteModel = Demeter.model('site')
  177. siteModel.id = info['site_id']
  178. site = siteModel.select(type='fetchone')
  179. status = True
  180. if info['status'] == 1 or info['status'] == 4:
  181. status = False
  182. if info and status == False:
  183. model.id = id
  184. update = {}
  185. update['status'] = 2
  186. model.update(update)
  187. if not File.exists(info['local']):
  188. self.download(info['file'], info['local'])
  189. if not File.exists(info['html']):
  190. #if info:
  191. handle = self.command(info)
  192. Shell.popen(handle)
  193. if File.exists(info['html']):
  194. # 截屏
  195. self.cut(info)
  196. #self.string_switch(info['html'], "taste", "tasting")
  197. # 获取有多少页
  198. page = self.total(info['path'])
  199. model.id = id
  200. size = os.path.getsize(info['local'])
  201. update = {}
  202. update['file_size'] = size
  203. update['page'] = page
  204. update['status'] = 3
  205. model.update(update)
  206. # 通知接口 通知应用成功转换
  207. info['page'] = page
  208. info['file_size'] = size
  209. info['convert_status'] = 1
  210. self.api(info, site)
  211. return
  212. model.id = id
  213. update = {}
  214. update['status'] = 4
  215. model.update(update)
  216. # 通知接口 通知应用失败转换
  217. info['page'] = 0
  218. info['file_size'] = 0
  219. info['convert_status'] = 2
  220. self.api(info, site)
  221. def api(self, info, site):
  222. if 'file_id' in info and info['file_id']:
  223. api = site['api']
  224. appid = site['appid']
  225. appsecret = site['appsecret']
  226. timestamp = Demeter.time()
  227. nonce = Demeter.hash()
  228. file = info['key']
  229. file_id = info['file_id']
  230. uid = info['uid']
  231. param = self.signature(site['id'], appid, appsecret, timestamp, nonce, file, file_id, uid)
  232. param['url'] = 'main/view'
  233. param['img'] = info['url'] + '.jpg'
  234. param['page'] = info['page']
  235. param['ext'] = info['ext']
  236. param['file_size'] = info['file_size']
  237. param['status'] = info['convert_status']
  238. Demeter.curl(api, param, 'post')
  239. def cut(self, info):
  240. from wand.image import Image
  241. pdf = Image(filename=info['pdf'], resolution=50)
  242. jpg = pdf.convert('jpg')
  243. req_image = []
  244. i = 0
  245. for img in jpg.sequence:
  246. if i == 0:
  247. img_page = Image(image=img)
  248. req_image.append(img_page.make_blob('jpg'))
  249. i = i+1
  250. dest = info['html']
  251. for img in req_image:
  252. ff = open(dest + '.jpg','wb')
  253. ff.write(img)
  254. ff.close()
  255. def string_switch(self, x,y,z,s=1):
  256. with open(x, "r", encoding="utf-8") as f:
  257. #readlines以列表的形式将文件读出
  258. lines = f.readlines()
  259. with open(x, "w", encoding="utf-8") as f_w:
  260. #定义一个数字,用来记录在读取文件时在列表中的位置
  261. n = 0
  262. #默认选项,只替换第一次匹配到的行中的字符串
  263. if s == 1:
  264. for line in lines:
  265. if y in line:
  266. line = line.replace(y,z)
  267. f_w.write(line)
  268. n += 1
  269. break
  270. f_w.write(line)
  271. n += 1
  272. #将剩余的文本内容继续输出
  273. for i in range(n,len(lines)):
  274. f_w.write(lines[i])
  275. #全局匹配替换
  276. elif s == 'g':
  277. for line in lines:
  278. if y in line:
  279. line = line.replace(y,z)
  280. f_w.write(line)