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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
|
# Copyright (c) 2017–2018 crocoite contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Controller classes, handling actions required for archival
"""
class ControllerSettings:
def __init__ (self, logBuffer=1000, maxBodySize=50*1024*1024, idleTimeout=2, timeout=10):
self.logBuffer = logBuffer
self.maxBodySize = maxBodySize
self.idleTimeout = idleTimeout
self.timeout = timeout
def toDict (self):
return dict (logBuffer=self.logBuffer, maxBodySize=self.maxBodySize,
idleTimeout=self.idleTimeout, timeout=self.timeout)
defaultSettings = ControllerSettings ()
import logging
from urllib.parse import urlsplit, urlunsplit
import pychrome
from . import behavior as cbehavior
from .browser import ChromeService
from .warc import WarcLoader, SerializingWARCWriter
from .util import getFormattedViewportMetrics
def firstOrNone (it):
""" Return first item of iterator it or None if empty """
try:
return next (it)
except StopIteration:
return None
class SinglePageController:
"""
Archive a single page url to file output.
"""
def __init__ (self, url, output, service=ChromeService (), behavior=cbehavior.available, \
logger=logging.getLogger(__name__), settings=defaultSettings):
self.url = url
self.output = output
self.service = service
self.behavior = behavior
self.settings = settings
self.logger = logger
def run (self):
ret = {'stats': None, 'links': []}
with self.service as browser:
browser = pychrome.Browser (url=browser)
writer = SerializingWARCWriter (self.output, gzip=True)
with WarcLoader (browser, self.url, writer,
logBuffer=self.settings.logBuffer,
maxBodySize=self.settings.maxBodySize) as l:
version = l.tab.Browser.getVersion ()
payload = {
'software': __package__,
'browser': version['product'],
'useragent': version['userAgent'],
'viewport': getFormattedViewportMetrics (l.tab),
}
warcinfo = writer.create_warcinfo_record (filename=None, info=payload)
writer.write_record (warcinfo)
# not all behavior scripts are allowed for every URL, filter them
enabledBehavior = list (filter (lambda x: self.url in x,
map (lambda x: x (l), self.behavior)))
linksBehavior = firstOrNone (filter (lambda x: isinstance (x, cbehavior.ExtractLinks),
enabledBehavior))
for b in enabledBehavior:
self.logger.debug ('starting onload behavior {}'.format (b.name))
b.onload ()
l.start ()
l.waitIdle (self.settings.idleTimeout, self.settings.timeout)
for b in enabledBehavior:
self.logger.debug ('starting onstop behavior {}'.format (b.name))
b.onstop ()
# if we stopped due to timeout, wait for remaining assets
l.waitIdle (2, 60)
l.stop ()
for b in enabledBehavior:
self.logger.debug ('starting onfinish behavior {}'.format (b.name))
b.onfinish ()
ret['stats'] = l.stats
ret['links'] = linksBehavior.links if linksBehavior else None
writer.flush ()
return ret
from collections import UserDict
class IntegerDict (UserDict):
""" Dict with dict/dict per-item arithmetic propagation, i.e. {1: 2}+{1: 1}={1: 3} """
def __add__ (self, b):
newdict = self.__class__ (self)
for k, v in b.items ():
if k in self:
newdict[k] += v
else:
newdict[k] = v
return newdict
class RecursionPolicy:
""" Abstract recursion policy """
def __call__ (self, urls):
raise NotImplementedError
class DepthLimit (RecursionPolicy):
"""
Limit recursion by depth.
depth==0 means no recursion, depth==1 is the page and outgoing links, …
"""
def __init__ (self, maxdepth=0):
self.maxdepth = maxdepth
def __call__ (self, urls):
if self.maxdepth <= 0:
return {}
else:
self.maxdepth -= 1
return urls
def __repr__ (self):
return '<DepthLimit {}>'.format (self.maxdepth)
class PrefixLimit (RecursionPolicy):
"""
Limit recursion by prefix
i.e. prefix=http://example.com/foo
ignored: http://example.com/bar http://offsite.example/foo
accepted: http://example.com/foobar http://example.com/foo/bar
"""
def __init__ (self, prefix):
self.prefix = prefix
def __call__ (self, urls):
return set (filter (lambda u: u.startswith (self.prefix), urls))
def removeFragment (u):
""" Remove fragment from url (i.e. #hashvalue) """
s = urlsplit (u)
return urlunsplit ((s.scheme, s.netloc, s.path, s.query, ''))
class RecursiveController:
"""
Simple recursive controller
Visits links acording to recursionPolicy
"""
def __init__ (self, url, output, service=ChromeService (), behavior=cbehavior.available, \
logger=logging.getLogger(__name__), settings=defaultSettings,
recursionPolicy=DepthLimit (0)):
self.url = url
self.output = output
self.service = service
self.behavior = behavior
self.settings = settings
self.logger = logger
self.recursionPolicy = recursionPolicy
def fetch (self, urls):
"""
Overrideable fetch action for URLs. Defaults to sequential
SinglePageController.
"""
result = []
for u in urls:
c = SinglePageController (u, self.output, self.service,
self.behavior, self.logger, self.settings)
result.append (c.run ())
return result
def run (self):
have = set ()
urls = set ([self.url])
ret = {'stats': IntegerDict ()}
while urls:
self.logger.info ('retrieving {} urls'.format (len (urls)))
result = self.fetch (urls)
have.update (urls)
urls = set ()
for r in result:
ret['stats'] += r['stats']
urls.update (map (removeFragment, r['links']))
urls.difference_update (have)
urls = self.recursionPolicy (urls)
# everything in ret must be serializeable
ret['stats'] = dict (ret['stats'])
return ret
|