File size: 12,714 Bytes
490e866
 
 
 
 
 
 
 
 
c7eced2
5675f95
490e866
 
 
 
5675f95
 
 
 
 
 
 
 
 
 
 
 
aeb21e9
5675f95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490e866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aeb21e9
eeb144a
490e866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b84661
 
 
 
490e866
 
 
 
 
 
 
 
 
 
 
 
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
"""Un-routed streaming transport acceptance for actual overlay removal."""
import contextlib
import json
import threading
import time
import unittest
import urllib.parse
from unittest.mock import patch

from tests.performance.test_reader_performance import StaticHandler, static_server, sync_playwright, PlaywrightError, minimal_pdf
from tests.reader.browser.test_reader_pdf_first_page import SOURCE, range_source, sparse_pdf


@unittest.skipIf(sync_playwright is None, 'Playwright is unavailable')
class ReaderCloseTrafficTests(unittest.TestCase):
    def test_reopen_pdf_paints_saved_page_from_validated_parent_ranges(self):
        with range_source(sparse_pdf(count=32, stride=16384)) as (origin, state, lock), sync_playwright() as playwright:
            state['block'].set()
            browser = playwright.chromium.launch(headless=True, args=['--no-sandbox'])
            try:
                page = browser.new_page(service_workers='block', viewport={'width': 390, 'height': 844})
                page.add_init_script('''const nativeFetch = window.fetch;
                  window.fetch = (input, init) => {
                    const url = new URL(input instanceof Request ? input.url : input, location.href);
                    return nativeFetch(url.pathname === '/api/reader-content' ? location.origin + url.pathname + url.search : input, init);
                  };''')
                page.goto(origin + '/static/manifest.json')
                page.add_script_tag(url=origin + '/static/reader/core/reader-contract.js')
                page.add_script_tag(url=origin + '/static/search/reader-host/application/navigation.js')
                reader_path = '/static/reader.html'
                target = origin + reader_path + '?' + urllib.parse.urlencode(dict(url=SOURCE, ext='pdf'))
                page.evaluate('''path => { window.navigationHost = VoiceOfMLReaderNavigation.createNavigation(path); }''', reader_path)
                frame = page.frame_locator('iframe.reader-overlay')
                phase = frame.locator('html[data-reader-phase="ready"]')
                for expected in (1, 19):
                    with lock:
                        state['requests'].clear()
                    page.evaluate('url => navigationHost.mount(new URL(url)) && true', target)
                    frame.locator(f'.reader-page[data-page="{expected}"] canvas.ready').wait_for(timeout=12000)
                    phase.wait_for(timeout=12000)
                    self.assertEqual(frame.locator('#page-number').input_value(), str(expected))
                    with lock:
                        ranges = state['requests'][:]
                    if expected == 1:
                        self.assertEqual(ranges[0], (0, 262143))
                        control = frame.locator('#page-number')
                        control.fill('19')
                        control.dispatch_event('change')
                        frame.locator('.reader-page[data-page="19"] canvas.ready').wait_for(timeout=12000)
                        page.evaluate('() => { navigationHost.unmount(); }')
                        page.locator('iframe.reader-overlay').wait_for(state='detached')
                        page.wait_for_function('''async url => (await VoiceOfMLReaderStore.get(url))?.page === 19''', arg=SOURCE)
                    else:
                        self.assertEqual(ranges[0], (0, 0))
                        self.assertNotIn((0, 262143), ranges)
            finally:
                browser.close()

    def test_close_mid_transfer_stops_bytes_and_next_book_opens(self):
        original = StaticHandler.do_GET
        lock = threading.Lock()
        transfers = []
        payload = minimal_pdf() + b'\0' * (8 * 1024 * 1024)
        source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/closing.pdf'

        def serve(handler):
            path = urllib.parse.urlsplit(handler.path)
            if path.path != '/api/reader-content':
                return original(handler)
            target = urllib.parse.parse_qs(path.query)['url'][0]
            if target.endswith('.txt'):
                body = b'Next book is readable'
                handler.send_response(200)
                handler.send_header('Content-Type', 'text/plain')
                handler.send_header('Content-Length', str(len(body)))
                handler.end_headers()
                handler.wfile.write(body)
                return
            record = {'sent': 0, 'done': False}
            with lock:
                transfers.append(record)
            try:
                handler.send_response(200)
                handler.send_header('Content-Type', 'application/pdf')
                handler.send_header('Content-Length', str(len(payload)))
                handler.send_header('Accept-Ranges', 'bytes')
                handler.end_headers()
                for offset in range(0, len(payload), 4096):
                    handler.wfile.write(payload[offset:offset+4096])
                    handler.wfile.flush()
                    with lock:
                        record['sent'] += 4096
                    time.sleep(.01)
            except (BrokenPipeError, ConnectionResetError):
                pass
            finally:
                with lock:
                    record['done'] = True

        with contextlib.ExitStack() as stack:
            stack.enter_context(patch.object(StaticHandler, 'do_GET', serve))
            origin = stack.enter_context(static_server())
            playwright = stack.enter_context(sync_playwright())
            try:
                browser = playwright.chromium.launch(headless=True, args=['--no-sandbox'])
            except PlaywrightError as error:
                raise unittest.SkipTest(str(error))
            stack.callback(browser.close)
            context = browser.new_context(service_workers='block')
            stack.callback(context.close)
            page = context.new_page()
            page.set_default_timeout(10000)
            page.add_init_script('''const nativeFetch=window.fetch;
              window.fetch=(input,init) => {
                const url=new URL(input instanceof Request?input.url:input,location.href);
                return nativeFetch(url.pathname==='/api/reader-content'?location.origin+url.pathname+url.search:input,init);
              };''')
            page.goto(origin+'/static/manifest.json')
            page.add_script_tag(url=origin+'/static/reader/core/reader-contract.js')
            page.add_script_tag(url=origin+'/static/search/reader-host/application/navigation.js')
            page.evaluate('''url => {
              window.__navigation = VoiceOfMLReaderNavigation.createNavigation('/static/reader.html');
              window.__reader = __navigation.mount(new URL(url));
            }''', origin+'/static/reader.html?'+urllib.parse.urlencode(dict(url=source, ext='pdf')))
            deadline = time.monotonic()+10
            while time.monotonic() < deadline:
                with lock:
                    started = any(row['sent'] > 0 for row in transfers)
                if started:
                    break
                page.wait_for_timeout(20)
            self.assertTrue(started)
            result = page.evaluate('''() => {
              let phase;
              __reader.contentWindow.addEventListener('voice-reader-dispose', () => {
                phase=__reader.contentDocument.documentElement.dataset.readerPhase;
              });
              __navigation.unmount();
              return phase;
            }''')
            self.assertEqual(result, 'disposed')
            with lock:
                before = sum(row['sent'] for row in transfers)
                count = len(transfers)
            page.wait_for_timeout(750)
            with lock:
                self.assertTrue(all(row['done'] for row in transfers), transfers)
                self.assertEqual(len(transfers), count)
                self.assertLess(sum(row['sent'] for row in transfers)-before, 65536)
            next_source = source.replace('.pdf', '.txt')
            page.evaluate('url => __navigation.mount(new URL(url))', origin+'/static/reader.html?'+urllib.parse.urlencode(dict(url=next_source, ext='txt')))
            frame = page.frame_locator('.reader-overlay')
            frame.locator('html[data-reader-phase="ready"]').wait_for()
            self.assertEqual(frame.locator('.reader-text').inner_text(), 'Next book is readable')

    def test_touch_tap_clears_selection_in_text_pdf_and_isolated_html(self):
        with contextlib.ExitStack() as stack:
            origin = stack.enter_context(static_server())
            playwright = stack.enter_context(sync_playwright())
            browser = playwright.chromium.launch(headless=True, args=['--no-sandbox'])
            stack.callback(browser.close)
            context = browser.new_context(has_touch=True, is_mobile=True, viewport={'width':390,'height':844})
            stack.callback(context.close)
            page = context.new_page()
            for extension in ('txt', 'html', 'pdf'):
                with self.subTest(extension=extension):
                    body = minimal_pdf() if extension == 'pdf' else b'<p>Selectable book text</p><p style="height:1600px">Other book text</p>'
                    page.route('**/api/reader-content?**', lambda route: route.fulfill(body=body, content_type='application/pdf' if extension == 'pdf' else 'text/html'))
                    source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/touch.'+extension
                    page.goto(origin+'/static/reader.html?'+urllib.parse.urlencode(dict(url=source, ext=extension)))
                    page.locator('html[data-reader-phase="ready"]').wait_for()
                    target = page.frame_locator('.html-frame').locator('p').first if extension == 'html' else page.locator('.reader-pdf-text-run' if extension == 'pdf' else '.reader-text').first
                    target.evaluate('''node => {
                      const doc=node.ownerDocument, range=doc.createRange();
                      range.selectNodeContents(node); doc.getSelection().removeAllRanges(); doc.getSelection().addRange(range);
                    }''')
                    self.assertTrue(target.evaluate('node => !!node.ownerDocument.getSelection().toString()'))
                    target.dispatch_event('pointerdown', {'pointerType':'touch','pointerId':41,'isPrimary':True,'clientX':100,'clientY':100})
                    page.wait_for_timeout(350)
                    target.dispatch_event('pointerup', {'pointerType':'touch','pointerId':41,'isPrimary':True,'clientX':100,'clientY':100})
                    self.assertTrue(target.evaluate('node => !!node.ownerDocument.getSelection().toString()'))
                    preserved = target.evaluate('''node => {
                      const doc=node.ownerDocument, selection=doc.getSelection(), output=[];
                      const send = (type, values={}) => node.dispatchEvent(new PointerEvent(type,
                        {bubbles:true, composed:true, pointerType:'touch', pointerId:41, isPrimary:true,
                         clientX:100,clientY:100,...values}));
                      for (const action of ['drag','cancel','changed','secondary']) {
                        const range=doc.createRange();range.selectNodeContents(node);
                        selection.removeAllRanges();selection.addRange(range);
                        send('pointerdown', action==='secondary'?{isPrimary:false}:{});
                        if (action==='drag') send('pointermove',{clientX:120});
                        if (action==='cancel') send('pointercancel');
                        if (action==='changed') {
                          const text = node.ownerDocument.createTreeWalker(node, NodeFilter.SHOW_TEXT).nextNode();
                          selection.setBaseAndExtent(text, 0, text, Math.min(3, text.data.length));
                        }
                        send('pointerup');
                        output.push(!!selection.toString());
                      }
                      const range=doc.createRange();range.selectNodeContents(node);
                      selection.removeAllRanges();selection.addRange(range);
                      return output;
                    }''')
                    self.assertEqual(preserved, [True]*4)
                    box = target.bounding_box()
                    page.touchscreen.tap(min(370, box['x']+box['width']-2), box['y']+min(box['height']-2, 20))
                    self.assertFalse(target.evaluate('node => !!node.ownerDocument.getSelection().toString()'))
                    page.unroute('**/api/reader-content?**')