Grishachev - mime-type

 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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
class Infile:
def __init__(self,infile):
self.data = []
self.f = open(infile,"rb")
self.readAll()
def getByte(self,position):
return self.data[position]
def readAll(self):
self.data = self.f.read()
def filetype(infile):
try:
f = Infile(infile)
types = [["image/png", [0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A]], ["image/jpg", [0xFF,0xD8,0xFF,0xE0]], ["image/jpg", [0xFF,0xD8,0xFF,0xE1]],
["image/gif", [0x47,0x49,0x46,0x38]], ["application/pdf", [0x25,0x50,0x44,0x46]], ["application/zip", [0x50,0x4B,0x03,0x04]],
["application/zip", [0x50,0x4B,0x4C,0x49,0x54,0x45]], ["application/zip", [0x50,0x4B,0x53,0x70,0x58]],
["application/zip", [0x50,0x4B,0x05,0x06]], ["application/zip", [0x50,0x4B,0x07,0x08]],
["application/zip", [0x57,0x69,0x6E,0x5A,0x69,0x70]], ["application/zip", [0x50,0x4B,0x03,0x04,0x14,0x00,0x01,0x00]],
["text/html", [0x3C,0x21,0x64,0x6F,0x63,0x74,0x79,0x70]], ["text/xml", [0x3C,0x3F,0x78,0x6D,0x6C,0x20]]]
temp_t = {}
idx = 0
while idx<len(types):
temp_t[idx] = True
idx += 1
i = 0
anybody = False
while True:
byte = f.getByte(i)
idx = 0
while idx<len(types):
if temp_t[idx]:
anybody = True
if len(types[idx][1])<=i:
return types[idx][0]
if types[idx][1][i] != byte:
temp_t[idx] = False
idx += 1
i+=1
if not anybody:
break
anybody = False
idx = 0
while idx<len(f.data):
byte = f.data[idx]
if byte == 0x0:
return "Error/Unknown"
idx += 1
return "text/plain"
except:
return "error/IOError"
print(filetype("book.pdf"))