80 lines
2.1 KiB
Python
80 lines
2.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""xlsx(zip) 读写的兼容层:修复 WPS 写坏的 ZIP64 条目大小。"""
|
|
import struct
|
|
import zipfile
|
|
|
|
|
|
def _local_sizes(fp, info):
|
|
fp.seek(info.header_offset)
|
|
hdr = fp.read(30)
|
|
if len(hdr) < 30 or hdr[:4] != b'PK\x03\x04':
|
|
return None, None
|
|
nlen, elen = struct.unpack('<HH', hdr[26:30])
|
|
fp.read(nlen)
|
|
extra = fp.read(elen)
|
|
usize = csize = None
|
|
i = 0
|
|
while i + 4 <= len(extra):
|
|
hid, hlen = struct.unpack('<HH', extra[i:i + 4])
|
|
body = extra[i + 4:i + 4 + hlen]
|
|
if hid == 0x0001:
|
|
if len(body) >= 16:
|
|
usize, csize = struct.unpack('<QQ', body[:16])
|
|
elif len(body) >= 8:
|
|
usize = struct.unpack('<Q', body[:8])[0]
|
|
i += 4 + hlen
|
|
return usize, csize
|
|
|
|
|
|
def repair_sizes(zf):
|
|
fixed = 0
|
|
fp = getattr(zf, 'fp', None)
|
|
if fp is None:
|
|
return 0
|
|
try:
|
|
if not fp.seekable():
|
|
return 0
|
|
except Exception:
|
|
return 0
|
|
try:
|
|
pos = fp.tell()
|
|
except Exception:
|
|
pos = None
|
|
for info in zf.infolist():
|
|
if info.compress_size != 0xFFFFFFFF and info.file_size != 0xFFFFFFFF:
|
|
continue
|
|
usize, csize = _local_sizes(fp, info)
|
|
if csize is None:
|
|
end = getattr(info, '_end_offset', None)
|
|
if end:
|
|
head = _peek(fp, info, 26, 4) or b'\x00\x00\x00\x00'
|
|
nlen, elen = struct.unpack('<HH', head)
|
|
csize = end - (info.header_offset + 30 + nlen + elen)
|
|
if csize is None:
|
|
continue
|
|
info.compress_size = csize
|
|
if usize:
|
|
info.file_size = usize
|
|
fixed += 1
|
|
if pos is not None:
|
|
try:
|
|
fp.seek(pos)
|
|
except Exception:
|
|
pass
|
|
return fixed
|
|
|
|
|
|
def _peek(fp, info, offset, size):
|
|
try:
|
|
fp.seek(info.header_offset + offset)
|
|
return fp.read(size)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def open_zip(path):
|
|
"""open + 修复 WPS 写坏的 zip64 条目大小,返回可正常读取的 ZipFile。"""
|
|
zf = zipfile.ZipFile(path)
|
|
repair_sizes(zf)
|
|
return zf
|