eric6/Helpviewer/UserAgent/UserAgentReader.py

branch
maintenance
changeset 7286
7eb04391adf7
parent 7226
babe80d84a3e
parent 7285
1ff497f33f31
child 7287
1c17f2191bdd
equal deleted inserted replaced
7226:babe80d84a3e 7286:7eb04391adf7
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2012 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6
7 """
8 Module implementing a class to read user agent data files.
9 """
10
11 from __future__ import unicode_literals
12
13 from PyQt5.QtCore import QXmlStreamReader, QIODevice, QFile, QCoreApplication
14
15
16 class UserAgentReader(QXmlStreamReader):
17 """
18 Class implementing a reader object for user agent data files.
19 """
20 def __init__(self):
21 """
22 Constructor
23 """
24 super(UserAgentReader, self).__init__()
25
26 def read(self, fileNameOrDevice):
27 """
28 Public method to read a user agent file.
29
30 @param fileNameOrDevice name of the file to read (string)
31 or reference to the device to read (QIODevice)
32 @return dictionary with user agent data (host as key, agent string as
33 value)
34 """
35 self.__agents = {}
36
37 if isinstance(fileNameOrDevice, QIODevice):
38 self.setDevice(fileNameOrDevice)
39 else:
40 f = QFile(fileNameOrDevice)
41 if not f.exists():
42 return self.__agents
43 f.open(QFile.ReadOnly)
44 self.setDevice(f)
45
46 while not self.atEnd():
47 self.readNext()
48 if self.isStartElement():
49 version = self.attributes().value("version")
50 if self.name() == "UserAgents" and \
51 (not version or version == "1.0"):
52 self.__readUserAgents()
53 else:
54 self.raiseError(QCoreApplication.translate(
55 "UserAgentReader",
56 "The file is not a UserAgents version 1.0 file."))
57
58 return self.__agents
59
60 def __readUserAgents(self):
61 """
62 Private method to read the user agents data.
63 """
64 if not self.isStartElement() and self.name() != "UserAgents":
65 return
66
67 while not self.atEnd():
68 self.readNext()
69 if self.isEndElement():
70 if self.name() == "UserAgent":
71 continue
72 else:
73 break
74
75 if self.isStartElement():
76 if self.name() == "UserAgent":
77 attributes = self.attributes()
78 host = attributes.value("host")
79 agent = attributes.value("agent")
80 self.__agents[host] = agent
81 else:
82 self.__skipUnknownElement()
83
84 def __skipUnknownElement(self):
85 """
86 Private method to skip over all unknown elements.
87 """
88 if not self.isStartElement():
89 return
90
91 while not self.atEnd():
92 self.readNext()
93 if self.isEndElement():
94 break
95
96 if self.isStartElement():
97 self.__skipUnknownElement()

eric ide

mercurial