diff --git a/Assets/Scripts/Core/DemoBot.Tube.cs b/Assets/Scripts/Core/DemoBot.Tube.cs new file mode 100644 index 0000000..fc540cd --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Tube.cs @@ -0,0 +1,77 @@ +using System.Collections; +using UnityEngine; + +namespace GrassCutter +{ + public partial class DemoBot + { + /// + /// -demoyt: a long YouTube video on the phone for well over the couple of minutes it used to stop at, what the page + /// thinks it runs in, the video full screen with the phone on its side, and the tool belt out of the way of the phone. + /// + IEnumerator TubeDemo() + { + TeamState.DeleteSave(); + yield return new WaitForSeconds(2f); + NetSession.Instance.HostLocal(); + while (!Me || !Ts) yield return null; + yield return new WaitForSeconds(2f); + var at = new Vector3(-16f, Soil + 0.1f, 14f); + Me.Teleport(at); + Me.LookAt(at + new Vector3(-6f, 1.4f, 9f)); + yield return new WaitForSeconds(0.8f); + var phone = Phone.I; + phone.Show(PhoneMode.Side); + yield return new WaitForSeconds(0.6f); + phone.Show(PhoneMode.Up); + yield return new WaitForSeconds(0.6f); + var scr = phone.Screen; + var web = scr.Web; + scr.Open("https://m.youtube.com/watch?v=aqz-KE-bpKQ"); + yield return Until(() => web.Url != null && web.Url.Contains("watch"), 30f); + yield return new WaitForSeconds(4f); + yield return Ask(web, "String(navigator.webdriver)+' '+(navigator.userAgentData?navigator.userAgentData.brands.map(b=>b.brand).join('/')+' '+navigator.userAgentData.platform+' mobile '+navigator.userAgentData.mobile:'no hints')"); + Log($"the page sees: webdriver {_said}"); + yield return Ask(web, "(()=>{const v=document.querySelector('video');if(!v)return 'no video';v.play().catch(()=>{});return 'playing'})()"); + BotCapture.From = null; + yield return Shot("yt_1_up"); + const string state = "(()=>{const v=document.querySelector('video');const e=document.querySelector('.ytp-error,ytm-player-error-message-renderer,.player-error,.ytp-error-content');" + + "return (v?Math.round(v.currentTime)+' s, paused '+v.paused:'no video')+(e&&e.offsetParent?' ERROR '+e.innerText.slice(0,90).replace(/\\s+/g,' '):'')})()"; + for (int i = 1; i <= (CommandLine.Has("-demoytlong") ? 10 : 1); i++) + { + yield return new WaitForSecondsRealtime(20f); + yield return Ask(web, state); + Log($"after {i * 20} s: {_said}"); + if (i == 5) yield return Shot("yt_2_100s"); + } + yield return Shot("yt_3_200s"); + + // on its side and full screen: the video must fill the page, square on + scr.Turn(); + yield return new WaitForSeconds(1.5f); + yield return Ask(web, "(()=>{const p=document.querySelector('.html5-video-player')||document.querySelector('video');if(!p)return Promise.resolve('nothing to fill');" + + "return p.requestFullscreen().then(()=>new Promise(r=>setTimeout(r,800))).then(()=>{const b=document.fullscreenElement.getBoundingClientRect();" + + "return 'full screen at '+Math.round(b.x)+','+Math.round(b.y)+' size '+Math.round(b.width)+'x'+Math.round(b.height)+', page '+innerWidth+'x'+innerHeight+', scrolled '+scrollY}).catch(e=>'refused: '+e.message)})()"); + Log($"wide, {_said} (phone css {web.CssW}x{web.CssH})"); + yield return Shot("yt_4_full"); + yield return Ask(web, state); + Log($"full screen: {_said}"); + // a page of our own that goes full screen on a real tap, the way a site's own button does + scr.Open("data:text/html," + + "
go full
" + + ""); + yield return Until(() => web.Url != null && web.Url.StartsWith("data:"), 15f); + yield return new WaitForSeconds(1.5f); + var tap = scr.PageAt(0.5f, 0.5f); + scr.Pointer(tap, true, true, false); + yield return null; + scr.Pointer(tap, false, false, true); + yield return new WaitForSeconds(1.5f); + yield return Ask(web, "(()=>{const f=document.fullscreenElement;if(!f)return 'not full screen '+(b.dataset.e||'');const r=f.getBoundingClientRect();return 'at '+Math.round(r.x)+','+Math.round(r.y)+' size '+Math.round(r.width)+'x'+Math.round(r.height)+', page '+innerWidth+'x'+innerHeight})()"); + Log($"full screen by a tap: {_said} (phone css {web.CssW}x{web.CssH})"); + yield return Shot("yt_5_tapfull"); + Log("yt done"); + Application.Quit(); + } + } +} diff --git a/Assets/Scripts/Core/DemoBot.Tube.cs.meta b/Assets/Scripts/Core/DemoBot.Tube.cs.meta new file mode 100644 index 0000000..ceb678b --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Tube.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 08498c5e737e424abacc3673ab39c783 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Core/DemoBot.cs b/Assets/Scripts/Core/DemoBot.cs index 615fe9e..fef9d8b 100644 --- a/Assets/Scripts/Core/DemoBot.cs +++ b/Assets/Scripts/Core/DemoBot.cs @@ -3078,6 +3078,11 @@ namespace GrassCutter yield return gameObject.AddComponent().Shoot(folder); yield break; } + if (CommandLine.Has("-demoyt")) + { + yield return TubeDemo(); + yield break; + } if (CommandLine.Has("-demophone")) { yield return PhoneTest(); diff --git a/Assets/Scripts/Core/PhoneWeb.cs b/Assets/Scripts/Core/PhoneWeb.cs index c76ee69..6cd0544 100644 --- a/Assets/Scripts/Core/PhoneWeb.cs +++ b/Assets/Scripts/Core/PhoneWeb.cs @@ -32,7 +32,27 @@ namespace GrassCutter "for(let i=0;i{const m=e.data&&e.data.__gc;if(m){s.vol=m[0];s.hold=m[1]}});" + "window.open=u=>{if(u)location.href=u;return window};" + - "addEventListener('click',e=>{const a=e.target.closest&&e.target.closest('a[target]');if(a)a.target='_self'},true)})()"; + "addEventListener('click',e=>{const a=e.target.closest&&e.target.closest('a[target]');if(a)a.target='_self'},true)})()"; + + /// + /// Full screen, done on the page itself: the element is pinned over the whole of the phone's page. The browser + /// runs without a window of its own, so the real thing was refused or came out the wrong size and shifted to + /// one side, and each site's fallback for that came out crooked in its own way. + /// + const string Full = + "(()=>{let fe=null,was=null,hid=[];const ev=e=>{for(const n of['fullscreenchange','webkitfullscreenchange'])e.dispatchEvent(new Event(n,{bubbles:true}))};" + + "const exit=function(){if(!fe)return Promise.resolve();const e=fe;fe=null;for(const[h,v]of hid)h.style.visibility=v;hid=[];if(was)e.setAttribute('style',was);else e.removeAttribute('style');ev(e);return Promise.resolve()};" + + "const enter=function(){if(fe===this)return Promise.resolve();if(fe)exit();fe=this;was=this.getAttribute('style');" + + "this.style.cssText+=';position:fixed!important;left:0!important;top:0!important;right:auto!important;bottom:auto!important;width:100vw!important;height:100vh!important;" + + "max-width:none!important;max-height:none!important;margin:0!important;transform:none!important;z-index:2147483647!important;background:#000!important';" + + // whatever else is on the page (a site's own header sits above the player) is hidden while it lasts + "for(let n=this;n&&n.parentElement;n=n.parentElement)for(const o of n.parentElement.children)if(o!==n){hid.push([o,o.style.visibility]);o.style.setProperty('visibility','hidden','important')}" + + "ev(this);return Promise.resolve()};" + + "for(const n of['requestFullscreen','webkitRequestFullscreen','webkitRequestFullScreen'])Element.prototype[n]=enter;" + + "HTMLVideoElement.prototype.webkitEnterFullscreen=enter;HTMLVideoElement.prototype.webkitEnterFullScreen=enter;" + + "for(const n of['exitFullscreen','webkitExitFullscreen','webkitCancelFullScreen'])Document.prototype[n]=exit;" + + "for(const n of['fullscreenElement','webkitFullscreenElement','webkitCurrentFullScreenElement'])Object.defineProperty(Document.prototype,n,{get:()=>fe,configurable:true});" + + "for(const n of['fullscreenEnabled','webkitFullscreenEnabled'])Object.defineProperty(Document.prototype,n,{get:()=>true,configurable:true})})()"; /// One running browser. A new one is made after a crash, so a late message from the old one can't touch it. sealed class Link @@ -154,9 +174,21 @@ namespace GrassCutter void Metrics() { string turned = _wide ? ",\"screenOrientation\":{\"type\":\"landscapePrimary\",\"angle\":90}" : ",\"screenOrientation\":{\"type\":\"portraitPrimary\",\"angle\":0}"; - Cmd("Emulation.setDeviceMetricsOverride", $"{{\"width\":{CssW},\"height\":{CssH},\"deviceScaleFactor\":2,\"mobile\":true{turned}}}"); + Cmd("Emulation.setDeviceMetricsOverride", $"{{\"width\":{CssW},\"height\":{CssH},\"screenWidth\":{CssW},\"screenHeight\":{CssH},\"deviceScaleFactor\":2,\"mobile\":true{turned}}}"); + Bounds(); } + /// + /// The browser's own window the size of the phone's page. A site going full screen fills the window, not the page + /// the phone shows, so with the window left at its start-up size the video came out shifted off to one side. + /// + void Bounds() + { + if (_winId > 0) Cmd("Browser.setWindowBounds", $"{{\"windowId\":{_winId},\"bounds\":{{\"width\":{CssW},\"height\":{CssH}}}}}"); + } + + volatile int _winAsk, _winId; + // ───────────────────────── fingers ───────────────────────── public void Touch(string type, float x, float y) @@ -231,7 +263,7 @@ namespace GrassCutter var done = new TaskCompletionSource(); if (!Ready) { done.TrySetResult(null); return done.Task; } _wait[id] = done; - Send(_link, "{\"id\":" + id + ",\"method\":\"Runtime.evaluate\",\"params\":{\"expression\":" + Str(js) + ",\"awaitPromise\":true}}"); + Send(_link, "{\"id\":" + id + ",\"method\":\"Runtime.evaluate\",\"params\":{\"expression\":" + Str(js) + ",\"awaitPromise\":true,\"userGesture\":true}}"); return done.Task; } @@ -394,7 +426,7 @@ namespace GrassCutter catch (UnauthorizedAccessException) { await Task.Delay(100); } } string args = "--headless=new --remote-debugging-port=0 --user-data-dir=\"" + _profile + "\" --no-first-run --no-default-browser-check " + - "--autoplay-policy=no-user-gesture-required --hide-crash-restore-bubble --disable-sync --disk-cache-size=157286400 --window-size=412,875 " + (_mute ? "--mute-audio " : "") + "about:blank"; + "--autoplay-policy=no-user-gesture-required --disable-blink-features=AutomationControlled --hide-crash-restore-bubble --disable-sync --disk-cache-size=157286400 --window-size=412,875 " + (_mute ? "--mute-audio " : "") + "about:blank"; link.Proc = Process.Start(new ProcessStartInfo(exe, args) { UseShellExecute = false, CreateNoWindow = true }); TieToGame(link); @@ -407,7 +439,7 @@ namespace GrassCutter } if (port == null) throw new TimeoutException("The browser didn't start."); - string ws, ua; + string ws, ua, chrome; using (var http = new HttpClient(new HttpClientHandler { UseProxy = false })) { // the debug server hangs up after each answer, so no reusing the connection @@ -423,7 +455,7 @@ namespace GrassCutter foreach (Match old in Regex.Matches(open, "\"id\"\\s*:\\s*\"([^\"]+)\"[^{}]*?\"type\"\\s*:\\s*\"page\"")) await http.GetAsync($"http://127.0.0.1:{port}/json/close/{old.Groups[1].Value}"); var version = await http.GetStringAsync($"http://127.0.0.1:{port}/json/version"); - string chrome = Regex.Match(version, "\"Browser\"\\s*:\\s*\"[^/]+/(\\d+)").Groups[1].Value; + chrome = Regex.Match(version, "\"Browser\"\\s*:\\s*\"[^/]+/(\\d+)").Groups[1].Value; ua = $"Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{chrome}.0.0.0 Mobile Safari/537.36"; } @@ -434,10 +466,18 @@ namespace GrassCutter _ = Task.Run(() => Receiver(link)); Send(link, "Page.enable", "{}"); - Send(link, "Emulation.setUserAgentOverride", "{\"userAgent\":" + Str(ua) + ",\"platform\":\"Linux armv8l\"}"); + // the whole of a phone's Chrome, client hints included: with only the agent string swapped, the hints still + // said HeadlessChrome on Windows, and YouTube stopped a video a couple of minutes in ("something went wrong") + string brands = $"[{{\"brand\":\"Chromium\",\"version\":\"{chrome}\"}},{{\"brand\":\"Google Chrome\",\"version\":\"{chrome}\"}},{{\"brand\":\"Not.A/Brand\",\"version\":\"99\"}}]"; + string full = $"[{{\"brand\":\"Chromium\",\"version\":\"{chrome}.0.0.0\"}},{{\"brand\":\"Google Chrome\",\"version\":\"{chrome}.0.0.0\"}},{{\"brand\":\"Not.A/Brand\",\"version\":\"99.0.0.0\"}}]"; + Send(link, "Emulation.setUserAgentOverride", "{\"userAgent\":" + Str(ua) + ",\"platform\":\"Linux armv8l\",\"userAgentMetadata\":{\"brands\":" + brands + + ",\"fullVersionList\":" + full + ",\"platform\":\"Android\",\"platformVersion\":\"14.0.0\",\"architecture\":\"\",\"model\":\"Pixel 8\",\"mobile\":true}}"); Send(link, "Emulation.setTouchEmulationEnabled", "{\"enabled\":true,\"maxTouchPoints\":5}"); Send(link, "Browser.setDownloadBehavior", "{\"behavior\":\"deny\"}"); - Send(link, "Page.addScriptToEvaluateOnNewDocument", "{\"source\":" + Str(Keep) + "}"); + Send(link, "Page.addScriptToEvaluateOnNewDocument", "{\"source\":" + Str(Keep + ";" + Full) + "}"); + int win = Interlocked.Increment(ref _id); + _winAsk = win; + Send(link, "{\"id\":" + win + ",\"method\":\"Browser.getWindowForTarget\",\"params\":{}}"); Metrics(); if (_shown) Screencast(true); link.Ready = true; @@ -504,7 +544,7 @@ namespace GrassCutter [Serializable] class Msg { public int id; public string method; public Params @params; public Outer result; } [Serializable] class Params { public string url, frameId; public FrameInfo frame; } [Serializable] class FrameInfo { public string url; public string parentId; } - [Serializable] class Outer { public Inner result; public string errorText; } + [Serializable] class Outer { public Inner result; public string errorText; public int windowId; } [Serializable] class Inner { public string value; } async Task Receiver(Link link) @@ -565,6 +605,7 @@ namespace GrassCutter { if (_wait.TryRemove(m.id, out var done)) done.TrySetResult(m.result?.result?.value); if (m.id == _navId && !string.IsNullOrEmpty(m.result?.errorText)) _navError = m.result.errorText; + if (m.id == _winAsk && m.result != null && m.result.windowId > 0) { _winId = m.result.windowId; Bounds(); } } else if (m.method == "Page.frameNavigated") { diff --git a/Assets/Scripts/UI/Hud.cs b/Assets/Scripts/UI/Hud.cs index 8aeb7a3..47c76e6 100644 --- a/Assets/Scripts/UI/Hud.cs +++ b/Assets/Scripts/UI/Hud.cs @@ -482,6 +482,9 @@ namespace GrassCutter _money.text = UIK.Money(_shownMoney); if (!ts || _local == null) return; + // the phone up at your face sits low in the view: the tool belt, the tool plate and the hint line step aside for it + var away = Phone.Focused ? Visibility.Hidden : Visibility.Visible; + if (_hotbar.style.visibility != away) { _hotbar.style.visibility = away; _plate.style.visibility = away; _hint.style.visibility = away; } RefreshHotbar(false); UpdatePlanet(ts); UpdateTool(ts);