summaryrefslogtreecommitdiff
path: root/crocoite/devtools.py
blob: ea46aaa525b47203ed13e701d2a9282b072a16e9 (plain)
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# Copyright (c) 2017 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.

"""
Communication with Google Chrome through its DevTools protocol.
"""

import json, asyncio, logging, os
from tempfile import mkdtemp
import shutil
import aiohttp, websockets
from yarl import URL

from .util import StrJsonEncoder

logger = logging.getLogger (__name__)

class Browser:
    """
    Communicate with Google Chrome through its DevTools protocol.
    
    Asynchronous context manager that creates a new Tab when entering.
    Destroyed upon exit.
    """

    __slots__ = ('session', 'url', 'tab', 'loop')

    def __init__ (self, url, loop=None):
        self.url = URL (url)
        self.session = None
        self.tab = None
        self.loop = loop

    async def __aiter__ (self):
        """ List all tabs """
        async with aiohttp.ClientSession (loop=self.loop) as session:
            async with session.get (self.url.with_path ('/json/list')) as r:
                resp = await r.json ()
                for tab in resp:
                    if tab['type'] == 'page':
                        yield tab

    async def __aenter__ (self):
        """ Create tab """
        assert self.tab is None
        assert self.session is None
        self.session = aiohttp.ClientSession (loop=self.loop)
        async with self.session.get (self.url.with_path ('/json/new')) as r:
            resp = await r.json ()
            self.tab = await Tab.create (**resp)
            return self.tab

    async def __aexit__ (self, *args):
        assert self.tab is not None
        assert self.session is not None
        await self.tab.close ()
        async with self.session.get (self.url.with_path (f'/json/close/{self.tab.id}')) as r:
            resp = await r.text ()
            assert resp == 'Target is closing'
        self.tab = None
        await self.session.close ()
        self.session = None
        return False

class TabFunction:
    """
    Helper class for infinite-depth tab functions.

    A method usually consists of namespace (Page, Network, …) and function name
    (getFoobar) separated by a dot. This class creates these function names
    while providing an intuitive Python interface (tab.Network.getFoobar).

    This was inspired by pychrome.
    """

    __slots__ = ('name', 'tab')

    def __init__ (self, name, tab):
        self.name = name
        self.tab = tab

    def __eq__ (self, b):
        assert isinstance (b, TabFunction)
        return self.name == b.name

    def __hash__ (self):
        return hash (self.name)

    def __getattr__ (self, k):
        return TabFunction (f'{self.name}.{k}', self.tab)

    async def __call__ (self, **kwargs):
        return await self.tab (self.name, **kwargs)

    def __repr__ (self):
        return f'<TabFunction {self.name}>'

class TabException (Exception):
    pass

class Crashed (TabException):
    pass

class MethodNotFound (TabException):
    pass

class InvalidParameter (TabException):
    pass

# map error codes to native exceptions
errorMap = {-32601: MethodNotFound, -32602: InvalidParameter}

class Tab:
    """
    Communicate with a single Google Chrome browser tab.
    """
    __slots__ = ('id', 'wsUrl', 'ws', 'msgid', 'transactions', 'queue', '_recvHandle', 'crashed')

    def __init__ (self, tabid, ws):
        """ Do not use this method, use Browser context manager. """
        self.id = tabid
        self.ws = ws
        self.msgid = 1
        self.crashed = False
        self.transactions = {}
        self.queue = asyncio.Queue ()

    def __getattr__ (self, k):
        return TabFunction (k, self)

    async def __call__ (self, method, **kwargs):
        """
        Actually call browser method with kwargs
        """

        if self.crashed or self._recvHandle.done ():
            raise Crashed ()

        msgid = self.msgid
        self.msgid += 1
        message = {'method': method, 'params': kwargs, 'id': msgid}
        t = self.transactions[msgid] = {'event': asyncio.Event (), 'result': None}
        logger.debug (f'← {message}')
        await self.ws.send (json.dumps (message, cls=StrJsonEncoder))
        await t['event'].wait ()
        ret = t['result']
        del self.transactions[msgid]
        if isinstance (ret, Exception):
            raise ret
        return ret

    async def _recvProcess (self):
        """
        Receive process that dispatches received websocket frames

        These are either events which will be put into a queue or request
        responses which unblock a __call__.
        """

        async def markCrashed (reason):
            # all pending requests can be considered failed since the
            # browser state is lost
            for v in self.transactions.values ():
                v['result'] = Crashed (reason)
                v['event'].set ()
            # and all future requests will fail as well until reloaded
            self.crashed = True
            await self.queue.put (Crashed (reason))

        while True:
            try:
                msg = await self.ws.recv ()
                msg = json.loads (msg)
            except Exception as e:
                # right now we cannot recover from this
                await markCrashed (e)
                break
            logger.debug (f'→ {msg}')
            if 'id' in msg:
                msgid = msg['id']
                t = self.transactions.get (msgid, None)
                if t is not None:
                    if 'error' in msg:
                        e = msg['error']
                        t['result'] = errorMap.get (e['code'], TabException) (e['code'], e['message'])
                    else:
                        t['result'] = msg['result']
                    t['event'].set ()
                else:
                    # ignore stale result
                    pass # pragma: no cover
            elif 'method' in msg:
                # special treatment
                if msg['method'] == 'Inspector.targetCrashed':
                    await markCrashed ('target')
                else:
                    await self.queue.put (msg)
            else:
                assert False # pragma: no cover

    async def run (self):
        self._recvHandle = asyncio.ensure_future (self._recvProcess ())

    async def close (self):
        self._recvHandle.cancel ()
        await self.ws.close ()
        # no join, throw away the queue. There will be nobody listening on the
        # other end.
        #await self.queue.join ()

    @property
    def pending (self):
        return self.queue.qsize ()

    async def get (self):
        def getattrRecursive (obj, name):
            if '.' in name:
                n, ext = name.split ('.', 1)
                return getattrRecursive (getattr (obj, n), ext)
            return getattr (obj, name)

        if self.crashed:
            raise Crashed ()

        ret = await self.queue.get ()
        if isinstance (ret, Exception):
            raise ret
        return getattrRecursive (self, ret['method']), ret['params']

    @classmethod
    async def create (cls, **kwargs):
        """ Async init """
        # increase size limit of a single frame to something ridiciously high,
        # so we can safely grab screenshots
        maxSize = 100*1024*1024 # 100 MB
        # chrome does not like pings and kills the connection, disable them
        ws = await websockets.connect(kwargs['webSocketDebuggerUrl'],
                max_size=maxSize, ping_interval=None)
        ret = cls (kwargs['id'], ws)
        await ret.run ()
        return ret

class Process:
    """ Start Google Chrome listening on a random port """

    __slots__ = ('binary', 'windowSize', 'p', 'userDataDir')

    def __init__ (self, binary='google-chrome-stable', windowSize=(1920, 1080)):
        self.binary = binary
        self.windowSize = windowSize
        self.p = None

    async def __aenter__ (self):
        assert self.p is None
        self.userDataDir = mkdtemp ()
        # see https://github.com/GoogleChrome/chrome-launcher/blob/master/docs/chrome-flags-for-tools.md
        args = [self.binary,
                '--window-size={},{}'.format (*self.windowSize),
                f'--user-data-dir={self.userDataDir}', # use temporory user dir
                '--no-default-browser-check',
                '--no-first-run', # don’t show first run screen
                '--disable-breakpad', # no error reports
                '--disable-extensions',
                '--disable-infobars',
                '--disable-notifications', # no libnotify
                '--disable-background-networking', # disable background services (updating, safe browsing, …)
                '--safebrowsing-disable-auto-update',
                '--disable-sync', # no google account syncing
                '--metrics-recording-only', # do not submit metrics
                '--disable-default-apps',
                '--disable-background-timer-throttling',
                '--disable-client-side-phishing-detection',
                '--disable-popup-blocking',
                '--disable-prompt-on-repost',
                '--enable-automation', # enable various automation-related things
                '--password-store=basic',
                '--headless',
                '--disable-gpu',
                '--hide-scrollbars', # hide scrollbars on screenshots
                '--mute-audio', # don’t play any audio
                '--remote-debugging-port=0', # pick a port. XXX: we may want to use --remote-debugging-pipe instead
                '--homepage=about:blank',
                'about:blank']
        # start new session, so ^C does not affect subprocess
        self.p = await asyncio.create_subprocess_exec (*args,
                stdout=asyncio.subprocess.DEVNULL,
                stderr=asyncio.subprocess.DEVNULL,
                stdin=asyncio.subprocess.DEVNULL,
                start_new_session=True)
        port = None
        # chrome writes its current active devtools port to a file. due to the
        # sleep() this is rather ugly, but should work with all versions of the
        # browser.
        for i in range (100):
            try:
                with open (os.path.join (self.userDataDir, 'DevToolsActivePort'), 'r') as fd:
                    port = int (fd.readline ().strip ())
                    break
            except FileNotFoundError:
                await asyncio.sleep (0.2)
        if port is None:
            raise Exception ('Chrome died on us.')

        return URL.build(scheme='http', host='localhost', port=port)

    async def __aexit__ (self, *exc):
        self.p.terminate ()
        await self.p.wait ()

        # Try to delete the temporary directory multiple times. It looks like
        # Chrome will change files in there even after it exited (i.e. .wait()
        # returned). Very strange.
        for i in range (5):
            try:
                shutil.rmtree (self.userDataDir)
                break
            except:
                await asyncio.sleep (0.2)

        self.p = None
        return False

class Passthrough:
    __slots__ = ('url', )

    def __init__ (self, url):
        self.url = URL (url)

    async def __aenter__ (self):
        return self.url

    async def __aexit__ (self, *exc):
        return False