diff --git a/Core.swift b/Core.swift new file mode 100644 index 0000000..6acb166 --- /dev/null +++ b/Core.swift @@ -0,0 +1,217 @@ +import Foundation + +private let readwisePathSegmentAllowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~")) + +private func isValidIPv4(_ labels: [Substring]) -> Bool { + guard labels.count == 4 else { return false } + return labels.allSatisfy { label in + guard !label.isEmpty, label.allSatisfy(\.isASCII), label.allSatisfy(\.isNumber) else { return false } + return UInt8(label) != nil + } +} + +private func isValidWebHost(_ host: String) -> Bool { + let lower = host.lowercased() + if lower.isEmpty { return false } + if lower == "localhost" { return true } + + // Bracketed IPv6 literals arrive in URLComponents.host either with or without brackets depending on OS version. + if lower.contains(":") { + let inner: Substring = (lower.hasPrefix("[") && lower.hasSuffix("]")) + ? lower.dropFirst().dropLast() + : lower[...] + let ipv6Allowed = CharacterSet(charactersIn: "0123456789abcdef:.") + return !inner.isEmpty && inner.contains(":") && inner.unicodeScalars.allSatisfy { ipv6Allowed.contains($0) } + } + + if lower.hasPrefix(".") || lower.hasSuffix(".") || lower.contains("..") { return false } + let labels = lower.split(separator: ".", omittingEmptySubsequences: false) + guard labels.count >= 2, labels.allSatisfy({ !$0.isEmpty }) else { return false } + + if labels.allSatisfy({ $0.allSatisfy(\.isNumber) }) { + return isValidIPv4(labels) + } + + for label in labels { + if label.hasPrefix("-") || label.hasSuffix("-") { return false } + for scalar in label.unicodeScalars { + if scalar.isASCII { + let c = Character(scalar) + if !(c.isLetter || c.isNumber || c == "-") { return false } + } + } + } + + guard let tld = labels.last else { return false } + if tld.hasPrefix("xn--") { + return tld.count >= 5 + } + return tld.count >= 2 && tld.allSatisfy(\.isLetter) +} + +func normalizeURL(_ raw: String) -> URL? { + var text = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty, text.rangeOfCharacter(from: .whitespacesAndNewlines) == nil else { return nil } + + if !text.contains("://") { + let authorityEnd = text.firstIndex(where: { $0 == "/" || $0 == "?" || $0 == "#" }) ?? text.endIndex + let authority = text[.. URL? { + var index = 0 + var afterDoubleDash = false + while index < arguments.count { + let arg = arguments[index] + if !afterDoubleDash && arg.hasPrefix("-") { + if arg == "--" { + afterDoubleDash = true + index += 1 + continue + } + if arg.hasPrefix("-psn_") || arg.contains("=") { + index += 1 + continue + } + // Skip macOS defaults key-value flag pairs (e.g. -AppleLanguages en, -NS* YES). + index += 1 + if index < arguments.count { + let next = arguments[index] + let lowerNext = next.lowercased() + if !next.hasPrefix("-") && !lowerNext.hasPrefix("http://") && !lowerNext.hasPrefix("https://") { + index += 1 + } + } + continue + } + if let url = normalizeURL(arg) { + return url + } + index += 1 + } + return nil +} + +func isAllowedExternalURL(_ url: URL) -> Bool { + guard let scheme = url.scheme?.lowercased() else { return false } + switch scheme { + case "http", "https": + return !(url.host ?? "").isEmpty + case "mailto": + let specifier = url.absoluteString.dropFirst("mailto:".count).trimmingCharacters(in: .whitespacesAndNewlines) + return !specifier.isEmpty + default: + return false + } +} + +func matchesExpectedReaderURL(_ requestURL: URL?, expected: URL?) -> Bool { + guard let requestURL else { return expected == nil } + if requestURL.absoluteString == "about:blank" { return true } + guard let expected else { return false } + if requestURL == expected { return true } + let reqPath = requestURL.path.isEmpty ? "/" : requestURL.path + let expPath = expected.path.isEmpty ? "/" : expected.path + return requestURL.scheme?.lowercased() == expected.scheme?.lowercased() + && requestURL.host?.lowercased() == expected.host?.lowercased() + && requestURL.port == expected.port + && reqPath == expPath + && requestURL.query == expected.query +} + +func readwiseEndpointURL(path: String, queryItems: [URLQueryItem]? = nil) -> URL? { + guard !path.isEmpty, !path.contains(".."), !path.contains("?"), !path.contains("#") else { return nil } + var components = URLComponents() + components.scheme = "https" + components.host = "readwise.io" + components.path = path.hasPrefix("/") ? path : "/" + path + if let queryItems, !queryItems.isEmpty { + components.queryItems = queryItems + } + guard let url = components.url, url.host?.lowercased() == "readwise.io" else { return nil } + return url +} + +func readwiseUpdateURL(docID: String) -> URL? { + guard !docID.isEmpty, + docID != ".", + !docID.contains(".."), + !docID.contains("/"), + !docID.contains("\\"), + let encoded = docID.addingPercentEncoding(withAllowedCharacters: readwisePathSegmentAllowed), + !encoded.isEmpty else { + return nil + } + var components = URLComponents() + components.scheme = "https" + components.host = "readwise.io" + components.percentEncodedPath = "/api/v3/update/\(encoded)/" + guard let url = components.url, url.host?.lowercased() == "readwise.io" else { return nil } + return url +} + +func readwiseReaderBaseURL() -> URL? { + var components = URLComponents() + components.scheme = "https" + components.host = "read.readwise.io" + return components.url +} + +// Keeps only readable top-level documents (no highlights, notes, PDFs, videos). +func slimDoc(_ raw: [String: Any]) -> [String: Any]? { + guard let id = raw["id"] as? String, !id.isEmpty, + raw["parent_id"] == nil || raw["parent_id"] is NSNull, + ["article", "email", "rss"].contains(raw["category"] as? String ?? "") else { return nil } + var out: [String: Any] = ["id": id] + for key in ["title", "author", "site_name", "source_url", "word_count", "reading_progress"] { + if let value = raw[key], !(value is NSNull) { out[key] = value } + } + return out +} + +func jsonLiteral(_ object: Any) -> String { + let valid = JSONSerialization.isValidJSONObject(object) + || object is String + || object is NSNumber + || object is Bool + || object is NSNull + guard valid, + let data = try? JSONSerialization.data(withJSONObject: object, options: .fragmentsAllowed), + let text = String(data: data, encoding: .utf8) else { return "{}" } + return text + .replacingOccurrences(of: " (bgHex: String, isDark: Bool?) { + switch theme?.lowercased() { + case "paper": + return ("#fbf9f4", false) + case "sepia": + return ("#f3ead6", false) + case "dark": + return ("#161616", true) + default: + return ("#fbf9f4", nil) + } +} diff --git a/Resources/Readability.js b/Resources/Readability.js index b745aa0..cbd0471 100644 --- a/Resources/Readability.js +++ b/Resources/Readability.js @@ -1,3 +1,8 @@ +/* + * @mozilla/readability v0.6.0 + * Source: https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz + * File: package/Readability.js + */ /* * Copyright (c) 2010 Arc90 Inc * @@ -30,7 +35,9 @@ function Readability(doc, options) { doc = options; options = arguments[2]; } else if (!doc || !doc.documentElement) { - throw new Error("First argument to Readability constructor should be a document object."); + throw new Error( + "First argument to Readability constructor should be a document object." + ); } options = options || {}; @@ -41,33 +48,41 @@ function Readability(doc, options) { this._articleDir = null; this._articleSiteName = null; this._attempts = []; + this._metadata = {}; // Configurable options this._debug = !!options.debug; - this._maxElemsToParse = options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE; - this._nbTopCandidates = options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES; + this._maxElemsToParse = + options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE; + this._nbTopCandidates = + options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES; this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD; - this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve || []); + this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat( + options.classesToPreserve || [] + ); this._keepClasses = !!options.keepClasses; - this._serializer = options.serializer || function(el) { - return el.innerHTML; - }; + this._serializer = + options.serializer || + function (el) { + return el.innerHTML; + }; this._disableJSONLD = !!options.disableJSONLD; this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos; + this._linkDensityModifier = options.linkDensityModifier || 0; // Start with all flags set - this._flags = this.FLAG_STRIP_UNLIKELYS | - this.FLAG_WEIGHT_CLASSES | - this.FLAG_CLEAN_CONDITIONALLY; - + this._flags = + this.FLAG_STRIP_UNLIKELYS | + this.FLAG_WEIGHT_CLASSES | + this.FLAG_CLEAN_CONDITIONALLY; // Control whether log messages are sent to the console if (this._debug) { - let logNode = function(node) { + let logNode = function (node) { if (node.nodeType == node.TEXT_NODE) { return `${node.nodeName} ("${node.textContent}")`; } - let attrPairs = Array.from(node.attributes || [], function(attr) { + let attrPairs = Array.from(node.attributes || [], function (attr) { return `${attr.name}="${attr.value}"`; }).join(" "); return `<${node.localName} ${attrPairs}>`; @@ -81,12 +96,15 @@ function Readability(doc, options) { return arg; }); args.unshift("Reader: (Readability)"); - console.log.apply(console, args); + // eslint-disable-next-line no-console + console.log(...args); } else if (typeof dump !== "undefined") { /* global dump */ - var msg = Array.prototype.map.call(arguments, function(x) { - return (x && x.nodeName) ? logNode(x) : x; - }).join(" "); + var msg = Array.prototype.map + .call(arguments, function (x) { + return x && x.nodeName ? logNode(x) : x; + }) + .join(" "); dump("Reader: (Readability) " + msg + "\n"); } }; @@ -112,7 +130,9 @@ Readability.prototype = { DEFAULT_N_TOP_CANDIDATES: 5, // Element tags to score by default. - DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","), + DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre" + .toUpperCase() + .split(","), // The default number of chars an article must have in order to return a result DEFAULT_CHAR_THRESHOLD: 500, @@ -122,16 +142,21 @@ Readability.prototype = { REGEXPS: { // NOTE: These two regular expressions are duplicated in // Readability-readerable.js. Please keep both copies in sync. - unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, + unlikelyCandidates: + /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i, - positive: /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i, - negative: /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i, - extraneous: /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i, + positive: + /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i, + negative: + /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|footer|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|widget/i, + extraneous: + /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i, byline: /byline|author|dateline|writtenby|p-author/i, replaceFonts: /<(\/?)font[^>]*>/gi, normalize: /\s{2,}/g, - videos: /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i, + videos: + /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i, shareElements: /(\b|_)(share|sharedaddy)(\b|_)/i, nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i, prevLink: /(prev|earl|old|new|<|«)/i, @@ -145,40 +170,111 @@ Readability.prototype = { // see: https://en.wikipedia.org/wiki/Comma#Comma_variants commas: /\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g, // See: https://schema.org/Article - jsonLdArticleTypes: /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/ + jsonLdArticleTypes: + /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/, + // used to see if a node's content matches words commonly used for ad blocks or loading indicators + adWords: + /^(ad(vertising|vertisement)?|pub(licité)?|werb(ung)?|广告|Реклама|Anuncio)$/iu, + loadingWords: + /^((loading|正在加载|Загрузка|chargement|cargando)(…|\.\.\.)?)$/iu, }, - UNLIKELY_ROLES: [ "menu", "menubar", "complementary", "navigation", "alert", "alertdialog", "dialog" ], - - DIV_TO_P_ELEMS: new Set([ "BLOCKQUOTE", "DL", "DIV", "IMG", "OL", "P", "PRE", "TABLE", "UL" ]), - - ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P"], + UNLIKELY_ROLES: [ + "menu", + "menubar", + "complementary", + "navigation", + "alert", + "alertdialog", + "dialog", + ], - PRESENTATIONAL_ATTRIBUTES: [ "align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "hspace", "rules", "style", "valign", "vspace" ], + DIV_TO_P_ELEMS: new Set([ + "BLOCKQUOTE", + "DL", + "DIV", + "IMG", + "OL", + "P", + "PRE", + "TABLE", + "UL", + ]), + + ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P", "OL", "UL"], + + PRESENTATIONAL_ATTRIBUTES: [ + "align", + "background", + "bgcolor", + "border", + "cellpadding", + "cellspacing", + "frame", + "hspace", + "rules", + "style", + "valign", + "vspace", + ], - DEPRECATED_SIZE_ATTRIBUTE_ELEMS: [ "TABLE", "TH", "TD", "HR", "PRE" ], + DEPRECATED_SIZE_ATTRIBUTE_ELEMS: ["TABLE", "TH", "TD", "HR", "PRE"], // The commented out elements qualify as phrasing content but tend to be // removed by readability when put into paragraphs, so we ignore them here. PHRASING_ELEMS: [ // "CANVAS", "IFRAME", "SVG", "VIDEO", - "ABBR", "AUDIO", "B", "BDO", "BR", "BUTTON", "CITE", "CODE", "DATA", - "DATALIST", "DFN", "EM", "EMBED", "I", "IMG", "INPUT", "KBD", "LABEL", - "MARK", "MATH", "METER", "NOSCRIPT", "OBJECT", "OUTPUT", "PROGRESS", "Q", - "RUBY", "SAMP", "SCRIPT", "SELECT", "SMALL", "SPAN", "STRONG", "SUB", - "SUP", "TEXTAREA", "TIME", "VAR", "WBR" + "ABBR", + "AUDIO", + "B", + "BDO", + "BR", + "BUTTON", + "CITE", + "CODE", + "DATA", + "DATALIST", + "DFN", + "EM", + "EMBED", + "I", + "IMG", + "INPUT", + "KBD", + "LABEL", + "MARK", + "MATH", + "METER", + "NOSCRIPT", + "OBJECT", + "OUTPUT", + "PROGRESS", + "Q", + "RUBY", + "SAMP", + "SCRIPT", + "SELECT", + "SMALL", + "SPAN", + "STRONG", + "SUB", + "SUP", + "TEXTAREA", + "TIME", + "VAR", + "WBR", ], // These are the classes that readability sets itself. - CLASSES_TO_PRESERVE: [ "page" ], + CLASSES_TO_PRESERVE: ["page"], // These are the list of HTML entities that need to be escaped. HTML_ESCAPE_MAP: { - "lt": "<", - "gt": ">", - "amp": "&", - "quot": '"', - "apos": "'", + lt: "<", + gt: ">", + amp: "&", + quot: '"', + apos: "'", }, /** @@ -186,8 +282,8 @@ Readability.prototype = { * * @param Element * @return void - **/ - _postProcessContent: function(articleContent) { + **/ + _postProcessContent(articleContent) { // Readability cannot open relative uris so we convert them to absolute uris. this._fixRelativeUris(articleContent); @@ -209,7 +305,7 @@ Readability.prototype = { * @param Function filterFn the function to use as a filter * @return void */ - _removeNodes: function(nodeList, filterFn) { + _removeNodes(nodeList, filterFn) { // Avoid ever operating on live node lists. if (this._docJSDOMParser && nodeList._isLiveNodeList) { throw new Error("Do not pass live node lists to _removeNodes"); @@ -232,7 +328,7 @@ Readability.prototype = { * @param String newTagName the new tag name to use * @return void */ - _replaceNodeTags: function(nodeList, newTagName) { + _replaceNodeTags(nodeList, newTagName) { // Avoid ever operating on live node lists. if (this._docJSDOMParser && nodeList._isLiveNodeList) { throw new Error("Do not pass live node lists to _replaceNodeTags"); @@ -253,7 +349,7 @@ Readability.prototype = { * @param Function fn The iterate function. * @return void */ - _forEachNode: function(nodeList, fn) { + _forEachNode(nodeList, fn) { Array.prototype.forEach.call(nodeList, fn, this); }, @@ -268,7 +364,7 @@ Readability.prototype = { * @param Function fn The test function. * @return void */ - _findNode: function(nodeList, fn) { + _findNode(nodeList, fn) { return Array.prototype.find.call(nodeList, fn, this); }, @@ -283,7 +379,7 @@ Readability.prototype = { * @param Function fn The iterate function. * @return Boolean */ - _someNode: function(nodeList, fn) { + _someNode(nodeList, fn) { return Array.prototype.some.call(nodeList, fn, this); }, @@ -298,33 +394,21 @@ Readability.prototype = { * @param Function fn The iterate function. * @return Boolean */ - _everyNode: function(nodeList, fn) { + _everyNode(nodeList, fn) { return Array.prototype.every.call(nodeList, fn, this); }, - /** - * Concat all nodelists passed as arguments. - * - * @return ...NodeList - * @return Array - */ - _concatNodeLists: function() { - var slice = Array.prototype.slice; - var args = slice.call(arguments); - var nodeLists = args.map(function(list) { - return slice.call(list); - }); - return Array.prototype.concat.apply([], nodeLists); - }, - - _getAllNodesWithTag: function(node, tagNames) { + _getAllNodesWithTag(node, tagNames) { if (node.querySelectorAll) { return node.querySelectorAll(tagNames.join(",")); } - return [].concat.apply([], tagNames.map(function(tag) { - var collection = node.getElementsByTagName(tag); - return Array.isArray(collection) ? collection : Array.from(collection); - })); + return [].concat.apply( + [], + tagNames.map(function (tag) { + var collection = node.getElementsByTagName(tag); + return Array.isArray(collection) ? collection : Array.from(collection); + }) + ); }, /** @@ -335,13 +419,11 @@ Readability.prototype = { * @param Element * @return void */ - _cleanClasses: function(node) { + _cleanClasses(node) { var classesToPreserve = this._classesToPreserve; var className = (node.getAttribute("class") || "") .split(/\s+/) - .filter(function(cls) { - return classesToPreserve.indexOf(cls) != -1; - }) + .filter(cls => classesToPreserve.includes(cls)) .join(" "); if (className) { @@ -355,6 +437,20 @@ Readability.prototype = { } }, + /** + * Tests whether a string is a URL or not. + * + * @param {string} str The string to test + * @return {boolean} true if str is a URL, false if not + */ + _isUrl(str) { + try { + new URL(str); + return true; + } catch { + return false; + } + }, /** * Converts each and uri in the given element to an absolute URI, * ignoring #ref URIs. @@ -362,7 +458,7 @@ Readability.prototype = { * @param Element * @return void */ - _fixRelativeUris: function(articleContent) { + _fixRelativeUris(articleContent) { var baseURI = this._doc.baseURI; var documentURI = this._doc.documentURI; function toAbsoluteURI(uri) { @@ -381,14 +477,17 @@ Readability.prototype = { } var links = this._getAllNodesWithTag(articleContent, ["a"]); - this._forEachNode(links, function(link) { + this._forEachNode(links, function (link) { var href = link.getAttribute("href"); if (href) { // Remove links with javascript: URIs, since // they won't work after scripts have been removed from the page. if (href.indexOf("javascript:") === 0) { // if the link only contains simple text content, it can be converted to a text node - if (link.childNodes.length === 1 && link.childNodes[0].nodeType === this.TEXT_NODE) { + if ( + link.childNodes.length === 1 && + link.childNodes[0].nodeType === this.TEXT_NODE + ) { var text = this._doc.createTextNode(link.textContent); link.parentNode.replaceChild(text, link); } else { @@ -406,10 +505,15 @@ Readability.prototype = { }); var medias = this._getAllNodesWithTag(articleContent, [ - "img", "picture", "figure", "video", "audio", "source" + "img", + "picture", + "figure", + "video", + "audio", + "source", ]); - this._forEachNode(medias, function(media) { + this._forEachNode(medias, function (media) { var src = media.getAttribute("src"); var poster = media.getAttribute("poster"); var srcset = media.getAttribute("srcset"); @@ -423,27 +527,37 @@ Readability.prototype = { } if (srcset) { - var newSrcset = srcset.replace(this.REGEXPS.srcsetUrl, function(_, p1, p2, p3) { - return toAbsoluteURI(p1) + (p2 || "") + p3; - }); + var newSrcset = srcset.replace( + this.REGEXPS.srcsetUrl, + function (_, p1, p2, p3) { + return toAbsoluteURI(p1) + (p2 || "") + p3; + } + ); media.setAttribute("srcset", newSrcset); } }); }, - _simplifyNestedElements: function(articleContent) { + _simplifyNestedElements(articleContent) { var node = articleContent; while (node) { - if (node.parentNode && ["DIV", "SECTION"].includes(node.tagName) && !(node.id && node.id.startsWith("readability"))) { + if ( + node.parentNode && + ["DIV", "SECTION"].includes(node.tagName) && + !(node.id && node.id.startsWith("readability")) + ) { if (this._isElementWithoutContent(node)) { node = this._removeAndGetNext(node); continue; - } else if (this._hasSingleTagInsideElement(node, "DIV") || this._hasSingleTagInsideElement(node, "SECTION")) { + } else if ( + this._hasSingleTagInsideElement(node, "DIV") || + this._hasSingleTagInsideElement(node, "SECTION") + ) { var child = node.children[0]; for (var i = 0; i < node.attributes.length; i++) { - child.setAttribute(node.attributes[i].name, node.attributes[i].value); + child.setAttributeNode(node.attributes[i].cloneNode()); } node.parentNode.replaceChild(child, node); node = child; @@ -460,7 +574,7 @@ Readability.prototype = { * * @return string **/ - _getArticleTitle: function() { + _getArticleTitle() { var doc = this._doc; var curTitle = ""; var origTitle = ""; @@ -469,9 +583,14 @@ Readability.prototype = { curTitle = origTitle = doc.title.trim(); // If they had an element with id "title" in their HTML - if (typeof curTitle !== "string") - curTitle = origTitle = this._getInnerText(doc.getElementsByTagName("title")[0]); - } catch (e) {/* ignore exceptions setting the title. */} + if (typeof curTitle !== "string") { + curTitle = origTitle = this._getInnerText( + doc.getElementsByTagName("title")[0] + ); + } + } catch (e) { + /* ignore exceptions setting the title. */ + } var titleHadHierarchicalSeparators = false; function wordCount(str) { @@ -479,23 +598,21 @@ Readability.prototype = { } // If there's a separator in the title, first remove the final part - if ((/ [\|\-\\\/>»] /).test(curTitle)) { + if (/ [\|\-\\\/>»] /.test(curTitle)) { titleHadHierarchicalSeparators = / [\\\/>»] /.test(curTitle); - curTitle = origTitle.replace(/(.*)[\|\-\\\/>»] .*/gi, "$1"); + let allSeparators = Array.from(origTitle.matchAll(/ [\|\-\\\/>»] /gi)); + curTitle = origTitle.substring(0, allSeparators.pop().index); - // If the resulting title is too short (3 words or fewer), remove - // the first part instead: - if (wordCount(curTitle) < 3) - curTitle = origTitle.replace(/[^\|\-\\\/>»]*[\|\-\\\/>»](.*)/gi, "$1"); - } else if (curTitle.indexOf(": ") !== -1) { + // If the resulting title is too short, remove the first part instead: + if (wordCount(curTitle) < 3) { + curTitle = origTitle.replace(/^[^\|\-\\\/>»]*[\|\-\\\/>»]/gi, ""); + } + } else if (curTitle.includes(": ")) { // Check if we have an heading containing this exact string, so we // could assume it's the full title. - var headings = this._concatNodeLists( - doc.getElementsByTagName("h1"), - doc.getElementsByTagName("h2") - ); + var headings = this._getAllNodesWithTag(doc, ["h1", "h2"]); var trimmedTitle = curTitle.trim(); - var match = this._someNode(headings, function(heading) { + var match = this._someNode(headings, function (heading) { return heading.textContent.trim() === trimmedTitle; }); @@ -515,8 +632,9 @@ Readability.prototype = { } else if (curTitle.length > 150 || curTitle.length < 15) { var hOnes = doc.getElementsByTagName("h1"); - if (hOnes.length === 1) + if (hOnes.length === 1) { curTitle = this._getInnerText(hOnes[0]); + } } curTitle = curTitle.trim().replace(this.REGEXPS.normalize, " "); @@ -525,9 +643,12 @@ Readability.prototype = { // title or we decreased the number of words by more than 1 word, use // the original title. var curTitleWordCount = wordCount(curTitle); - if (curTitleWordCount <= 4 && - (!titleHadHierarchicalSeparators || - curTitleWordCount != wordCount(origTitle.replace(/[\|\-\\\/>»]+/g, "")) - 1)) { + if ( + curTitleWordCount <= 4 && + (!titleHadHierarchicalSeparators || + curTitleWordCount != + wordCount(origTitle.replace(/[\|\-\\\/>»]+/g, "")) - 1) + ) { curTitle = origTitle; } @@ -540,7 +661,7 @@ Readability.prototype = { * * @return void **/ - _prepDocument: function() { + _prepDocument() { var doc = this._doc; // Remove all style tags in head @@ -558,11 +679,13 @@ Readability.prototype = { * whitespace in between. If the given node is an element, the same node is * returned. */ - _nextNode: function (node) { + _nextNode(node) { var next = node; - while (next - && (next.nodeType != this.ELEMENT_NODE) - && this.REGEXPS.whitespace.test(next.textContent)) { + while ( + next && + next.nodeType != this.ELEMENT_NODE && + this.REGEXPS.whitespace.test(next.textContent) + ) { next = next.nextSibling; } return next; @@ -575,8 +698,8 @@ Readability.prototype = { * will become: *
foo
bar

abc

*/ - _replaceBrs: function (elem) { - this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function(br) { + _replaceBrs(elem) { + this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function (br) { var next = br.nextSibling; // Whether 2 or more
elements have been found and replaced with a @@ -586,10 +709,10 @@ Readability.prototype = { // If we find a
chain, remove the
s until we hit another node // or non-whitespace. This leaves behind the first
in the chain // (which will be replaced with a

later). - while ((next = this._nextNode(next)) && (next.tagName == "BR")) { + while ((next = this._nextNode(next)) && next.tagName == "BR") { replaced = true; var brSibling = next.nextSibling; - next.parentNode.removeChild(next); + next.remove(); next = brSibling; } @@ -605,12 +728,14 @@ Readability.prototype = { // If we've hit another

, we're done adding children to this

. if (next.tagName == "BR") { var nextElem = this._nextNode(next.nextSibling); - if (nextElem && nextElem.tagName == "BR") + if (nextElem && nextElem.tagName == "BR") { break; + } } - if (!this._isPhrasingContent(next)) + if (!this._isPhrasingContent(next)) { break; + } // Otherwise, make this node a child of the new

. var sibling = next.nextSibling; @@ -619,16 +744,17 @@ Readability.prototype = { } while (p.lastChild && this._isWhitespace(p.lastChild)) { - p.removeChild(p.lastChild); + p.lastChild.remove(); } - if (p.parentNode.tagName === "P") + if (p.parentNode.tagName === "P") { this._setNodeTag(p.parentNode, "DIV"); + } } }); }, - _setNodeTag: function (node, tag) { + _setNodeTag(node, tag) { this.log("_setNodeTag", node, tag); if (this._docJSDOMParser) { node.localName = tag.toLowerCase(); @@ -641,20 +767,12 @@ Readability.prototype = { replacement.appendChild(node.firstChild); } node.parentNode.replaceChild(replacement, node); - if (node.readability) + if (node.readability) { replacement.readability = node.readability; + } for (var i = 0; i < node.attributes.length; i++) { - try { - replacement.setAttribute(node.attributes[i].name, node.attributes[i].value); - } catch (ex) { - /* it's possible for setAttribute() to throw if the attribute name - * isn't a valid XML Name. Such attributes can however be parsed from - * source in HTML docs, see https://github.com/whatwg/html/issues/4275, - * so we can hit them here and then throw. We don't care about such - * attributes so we ignore them. - */ - } + replacement.setAttributeNode(node.attributes[i].cloneNode()); } return replacement; }, @@ -666,7 +784,7 @@ Readability.prototype = { * @param Element * @return void **/ - _prepArticle: function(articleContent) { + _prepArticle(articleContent) { this._cleanStyles(articleContent); // Check for data tables before we continue, to avoid removing items in @@ -692,7 +810,10 @@ Readability.prototype = { this._forEachNode(articleContent.children, function (topCandidate) { this._cleanMatchedNodes(topCandidate, function (node, matchString) { - return this.REGEXPS.shareElements.test(matchString) && node.textContent.length < shareElementThreshold; + return ( + this.REGEXPS.shareElements.test(matchString) && + node.textContent.length < shareElementThreshold + ); }); }); @@ -710,38 +831,61 @@ Readability.prototype = { this._cleanConditionally(articleContent, "div"); // replace H1 with H2 as H1 should be only title that is displayed separately - this._replaceNodeTags(this._getAllNodesWithTag(articleContent, ["h1"]), "h2"); + this._replaceNodeTags( + this._getAllNodesWithTag(articleContent, ["h1"]), + "h2" + ); // Remove extra paragraphs - this._removeNodes(this._getAllNodesWithTag(articleContent, ["p"]), function (paragraph) { - var imgCount = paragraph.getElementsByTagName("img").length; - var embedCount = paragraph.getElementsByTagName("embed").length; - var objectCount = paragraph.getElementsByTagName("object").length; - // At this point, nasty iframes have been removed, only remain embedded video ones. - var iframeCount = paragraph.getElementsByTagName("iframe").length; - var totalCount = imgCount + embedCount + objectCount + iframeCount; - - return totalCount === 0 && !this._getInnerText(paragraph, false); - }); - - this._forEachNode(this._getAllNodesWithTag(articleContent, ["br"]), function(br) { - var next = this._nextNode(br.nextSibling); - if (next && next.tagName == "P") - br.parentNode.removeChild(br); - }); + this._removeNodes( + this._getAllNodesWithTag(articleContent, ["p"]), + function (paragraph) { + // At this point, nasty iframes have been removed; only embedded video + // ones remain. + var contentElementCount = this._getAllNodesWithTag(paragraph, [ + "img", + "embed", + "object", + "iframe", + ]).length; + return ( + contentElementCount === 0 && !this._getInnerText(paragraph, false) + ); + } + ); + + this._forEachNode( + this._getAllNodesWithTag(articleContent, ["br"]), + function (br) { + var next = this._nextNode(br.nextSibling); + if (next && next.tagName == "P") { + br.remove(); + } + } + ); // Remove single-cell tables - this._forEachNode(this._getAllNodesWithTag(articleContent, ["table"]), function(table) { - var tbody = this._hasSingleTagInsideElement(table, "TBODY") ? table.firstElementChild : table; - if (this._hasSingleTagInsideElement(tbody, "TR")) { - var row = tbody.firstElementChild; - if (this._hasSingleTagInsideElement(row, "TD")) { - var cell = row.firstElementChild; - cell = this._setNodeTag(cell, this._everyNode(cell.childNodes, this._isPhrasingContent) ? "P" : "DIV"); - table.parentNode.replaceChild(cell, table); + this._forEachNode( + this._getAllNodesWithTag(articleContent, ["table"]), + function (table) { + var tbody = this._hasSingleTagInsideElement(table, "TBODY") + ? table.firstElementChild + : table; + if (this._hasSingleTagInsideElement(tbody, "TR")) { + var row = tbody.firstElementChild; + if (this._hasSingleTagInsideElement(row, "TD")) { + var cell = row.firstElementChild; + cell = this._setNodeTag( + cell, + this._everyNode(cell.childNodes, this._isPhrasingContent) + ? "P" + : "DIV" + ); + table.parentNode.replaceChild(cell, table); + } } } - }); + ); }, /** @@ -750,9 +894,9 @@ Readability.prototype = { * * @param Element * @return void - **/ - _initializeNode: function(node) { - node.readability = {"contentScore": 0}; + **/ + _initializeNode(node) { + node.readability = { contentScore: 0 }; switch (node.tagName) { case "DIV": @@ -790,9 +934,9 @@ Readability.prototype = { node.readability.contentScore += this._getClassWeight(node); }, - _removeAndGetNext: function(node) { + _removeAndGetNext(node) { var nextNode = this._getNextNode(node, true); - node.parentNode.removeChild(node); + node.remove(); return nextNode; }, @@ -802,8 +946,12 @@ Readability.prototype = { * (and its kids) are going away, and we want the next node over. * * Calling this in a loop will traverse the DOM depth-first. + * + * @param {Element} node + * @param {boolean} ignoreSelfAndKids + * @return {Element} */ - _getNextNode: function(node, ignoreSelfAndKids) { + _getNextNode(node, ignoreSelfAndKids) { // First check for kids if those aren't being ignored if (!ignoreSelfAndKids && node.firstElementChild) { return node.firstElementChild; @@ -825,9 +973,15 @@ Readability.prototype = { // 1 = same text, 0 = completely different text // works the way that it splits both texts into words and then finds words that are unique in second text // the result is given by the lower length of unique parts - _textSimilarity: function(textA, textB) { - var tokensA = textA.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean); - var tokensB = textB.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean); + _textSimilarity(textA, textB) { + var tokensA = textA + .toLowerCase() + .split(this.REGEXPS.tokenize) + .filter(Boolean); + var tokensB = textB + .toLowerCase() + .split(this.REGEXPS.tokenize) + .filter(Boolean); if (!tokensA.length || !tokensB.length) { return 0; } @@ -836,31 +990,36 @@ Readability.prototype = { return 1 - distanceB; }, - _checkByline: function(node, matchString) { - if (this._articleByline) { - return false; - } - - if (node.getAttribute !== undefined) { - var rel = node.getAttribute("rel"); - var itemprop = node.getAttribute("itemprop"); - } - - if ((rel === "author" || (itemprop && itemprop.indexOf("author") !== -1) || this.REGEXPS.byline.test(matchString)) && this._isValidByline(node.textContent)) { - this._articleByline = node.textContent.trim(); - return true; - } - - return false; + /** + * Checks whether an element node contains a valid byline + * + * @param node {Element} + * @param matchString {string} + * @return boolean + */ + _isValidByline(node, matchString) { + var rel = node.getAttribute("rel"); + var itemprop = node.getAttribute("itemprop"); + var bylineLength = node.textContent.trim().length; + + return ( + (rel === "author" || + (itemprop && itemprop.includes("author")) || + this.REGEXPS.byline.test(matchString)) && + !!bylineLength && + bylineLength < 100 + ); }, - _getNodeAncestors: function(node, maxDepth) { + _getNodeAncestors(node, maxDepth) { maxDepth = maxDepth || 0; - var i = 0, ancestors = []; + var i = 0, + ancestors = []; while (node.parentNode) { ancestors.push(node.parentNode); - if (maxDepth && ++i === maxDepth) + if (maxDepth && ++i === maxDepth) { break; + } node = node.parentNode; } return ancestors; @@ -872,8 +1031,9 @@ Readability.prototype = { * * @param page a document to run upon. Needs to be a full document, complete with body. * @return Element - **/ - _grabArticle: function (page) { + **/ + /* eslint-disable-next-line complexity */ + _grabArticle(page) { this.log("**** grabArticle ****"); var doc = this._doc; var isPaging = page !== null; @@ -889,7 +1049,9 @@ Readability.prototype = { while (true) { this.log("Starting grabArticle loop"); - var stripUnlikelyCandidates = this._flagIsActive(this.FLAG_STRIP_UNLIKELYS); + var stripUnlikelyCandidates = this._flagIsActive( + this.FLAG_STRIP_UNLIKELYS + ); // First, node prepping. Trash nodes that look cruddy (like ones with the // class name "comment", etc), and turn divs into P tags where they have been @@ -900,7 +1062,6 @@ Readability.prototype = { let shouldRemoveTitleHeader = true; while (node) { - if (node.tagName === "HTML") { this._articleLang = node.getAttribute("lang"); } @@ -914,19 +1075,44 @@ Readability.prototype = { } // User is not able to see elements applied with both "aria-modal = true" and "role = dialog" - if (node.getAttribute("aria-modal") == "true" && node.getAttribute("role") == "dialog") { + if ( + node.getAttribute("aria-modal") == "true" && + node.getAttribute("role") == "dialog" + ) { node = this._removeAndGetNext(node); continue; } - // Check to see if this node is a byline, and remove it if it is. - if (this._checkByline(node, matchString)) { + // If we don't have a byline yet check to see if this node is a byline; if it is store the byline and remove the node. + if ( + !this._articleByline && + !this._metadata.byline && + this._isValidByline(node, matchString) + ) { + // Find child node matching [itemprop="name"] and use that if it exists for a more accurate author name byline + var endOfSearchMarkerNode = this._getNextNode(node, true); + var next = this._getNextNode(node); + var itemPropNameNode = null; + while (next && next != endOfSearchMarkerNode) { + var itemprop = next.getAttribute("itemprop"); + if (itemprop && itemprop.includes("name")) { + itemPropNameNode = next; + break; + } else { + next = this._getNextNode(next); + } + } + this._articleByline = (itemPropNameNode ?? node).textContent.trim(); node = this._removeAndGetNext(node); continue; } if (shouldRemoveTitleHeader && this._headerDuplicatesTitle(node)) { - this.log("Removing header: ", node.textContent.trim(), this._articleTitle.trim()); + this.log( + "Removing header: ", + node.textContent.trim(), + this._articleTitle.trim() + ); shouldRemoveTitleHeader = false; node = this._removeAndGetNext(node); continue; @@ -934,34 +1120,49 @@ Readability.prototype = { // Remove unlikely candidates if (stripUnlikelyCandidates) { - if (this.REGEXPS.unlikelyCandidates.test(matchString) && - !this.REGEXPS.okMaybeItsACandidate.test(matchString) && - !this._hasAncestorTag(node, "table") && - !this._hasAncestorTag(node, "code") && - node.tagName !== "BODY" && - node.tagName !== "A") { + if ( + this.REGEXPS.unlikelyCandidates.test(matchString) && + !this.REGEXPS.okMaybeItsACandidate.test(matchString) && + !this._hasAncestorTag(node, "table") && + !this._hasAncestorTag(node, "code") && + node.tagName !== "BODY" && + node.tagName !== "A" + ) { this.log("Removing unlikely candidate - " + matchString); node = this._removeAndGetNext(node); continue; } if (this.UNLIKELY_ROLES.includes(node.getAttribute("role"))) { - this.log("Removing content with role " + node.getAttribute("role") + " - " + matchString); + this.log( + "Removing content with role " + + node.getAttribute("role") + + " - " + + matchString + ); node = this._removeAndGetNext(node); continue; } } // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe). - if ((node.tagName === "DIV" || node.tagName === "SECTION" || node.tagName === "HEADER" || - node.tagName === "H1" || node.tagName === "H2" || node.tagName === "H3" || - node.tagName === "H4" || node.tagName === "H5" || node.tagName === "H6") && - this._isElementWithoutContent(node)) { + if ( + (node.tagName === "DIV" || + node.tagName === "SECTION" || + node.tagName === "HEADER" || + node.tagName === "H1" || + node.tagName === "H2" || + node.tagName === "H3" || + node.tagName === "H4" || + node.tagName === "H5" || + node.tagName === "H6") && + this._isElementWithoutContent(node) + ) { node = this._removeAndGetNext(node); continue; } - if (this.DEFAULT_TAGS_TO_SCORE.indexOf(node.tagName) !== -1) { + if (this.DEFAULT_TAGS_TO_SCORE.includes(node.tagName)) { elementsToScore.push(node); } @@ -982,7 +1183,7 @@ Readability.prototype = { } } else if (p !== null) { while (p.lastChild && this._isWhitespace(p.lastChild)) { - p.removeChild(p.lastChild); + p.lastChild.remove(); } p = null; } @@ -993,7 +1194,10 @@ Readability.prototype = { // element. DIVs with only a P element inside and no text content can be // safely converted into plain P elements to avoid confusing the scoring // algorithm with DIVs with are, in practice, paragraphs. - if (this._hasSingleTagInsideElement(node, "P") && this._getLinkDensity(node) < 0.25) { + if ( + this._hasSingleTagInsideElement(node, "P") && + this._getLinkDensity(node) < 0.25 + ) { var newNode = node.children[0]; node.parentNode.replaceChild(newNode, node); node = newNode; @@ -1011,21 +1215,27 @@ Readability.prototype = { * Then add their score to their parent node. * * A score is determined by things like number of commas, class names, etc. Maybe eventually link density. - **/ + **/ var candidates = []; - this._forEachNode(elementsToScore, function(elementToScore) { - if (!elementToScore.parentNode || typeof(elementToScore.parentNode.tagName) === "undefined") + this._forEachNode(elementsToScore, function (elementToScore) { + if ( + !elementToScore.parentNode || + typeof elementToScore.parentNode.tagName === "undefined" + ) { return; + } // If this paragraph is less than 25 characters, don't even count it. var innerText = this._getInnerText(elementToScore); - if (innerText.length < 25) + if (innerText.length < 25) { return; + } // Exclude nodes with no ancestor. var ancestors = this._getNodeAncestors(elementToScore, 5); - if (ancestors.length === 0) + if (ancestors.length === 0) { return; + } var contentScore = 0; @@ -1039,11 +1249,16 @@ Readability.prototype = { contentScore += Math.min(Math.floor(innerText.length / 100), 3); // Initialize and score ancestors. - this._forEachNode(ancestors, function(ancestor, level) { - if (!ancestor.tagName || !ancestor.parentNode || typeof(ancestor.parentNode.tagName) === "undefined") + this._forEachNode(ancestors, function (ancestor, level) { + if ( + !ancestor.tagName || + !ancestor.parentNode || + typeof ancestor.parentNode.tagName === "undefined" + ) { return; + } - if (typeof(ancestor.readability) === "undefined") { + if (typeof ancestor.readability === "undefined") { this._initializeNode(ancestor); candidates.push(ancestor); } @@ -1052,12 +1267,13 @@ Readability.prototype = { // - parent: 1 (no division) // - grandparent: 2 // - great grandparent+: ancestor level * 3 - if (level === 0) + if (level === 0) { var scoreDivider = 1; - else if (level === 1) + } else if (level === 1) { scoreDivider = 2; - else + } else { scoreDivider = level * 3; + } ancestor.readability.contentScore += contentScore / scoreDivider; }); }); @@ -1071,7 +1287,9 @@ Readability.prototype = { // Scale the final candidates score based on link density. Good content // should have a relatively small link density (5% or less) and be mostly // unaffected by this operation. - var candidateScore = candidate.readability.contentScore * (1 - this._getLinkDensity(candidate)); + var candidateScore = + candidate.readability.contentScore * + (1 - this._getLinkDensity(candidate)); candidate.readability.contentScore = candidateScore; this.log("Candidate:", candidate, "with score " + candidateScore); @@ -1079,10 +1297,14 @@ Readability.prototype = { for (var t = 0; t < this._nbTopCandidates; t++) { var aTopCandidate = topCandidates[t]; - if (!aTopCandidate || candidateScore > aTopCandidate.readability.contentScore) { + if ( + !aTopCandidate || + candidateScore > aTopCandidate.readability.contentScore + ) { topCandidates.splice(t, 0, candidate); - if (topCandidates.length > this._nbTopCandidates) + if (topCandidates.length > this._nbTopCandidates) { topCandidates.pop(); + } break; } } @@ -1113,8 +1335,14 @@ Readability.prototype = { // and whose scores are quite closed with current `topCandidate` node. var alternativeCandidateAncestors = []; for (var i = 1; i < topCandidates.length; i++) { - if (topCandidates[i].readability.contentScore / topCandidate.readability.contentScore >= 0.75) { - alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i])); + if ( + topCandidates[i].readability.contentScore / + topCandidate.readability.contentScore >= + 0.75 + ) { + alternativeCandidateAncestors.push( + this._getNodeAncestors(topCandidates[i]) + ); } } var MINIMUM_TOPCANDIDATES = 3; @@ -1122,8 +1350,17 @@ Readability.prototype = { parentOfTopCandidate = topCandidate.parentNode; while (parentOfTopCandidate.tagName !== "BODY") { var listsContainingThisAncestor = 0; - for (var ancestorIndex = 0; ancestorIndex < alternativeCandidateAncestors.length && listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; ancestorIndex++) { - listsContainingThisAncestor += Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate)); + for ( + var ancestorIndex = 0; + ancestorIndex < alternativeCandidateAncestors.length && + listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; + ancestorIndex++ + ) { + listsContainingThisAncestor += Number( + alternativeCandidateAncestors[ancestorIndex].includes( + parentOfTopCandidate + ) + ); } if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) { topCandidate = parentOfTopCandidate; @@ -1153,8 +1390,9 @@ Readability.prototype = { continue; } var parentScore = parentOfTopCandidate.readability.contentScore; - if (parentScore < scoreThreshold) + if (parentScore < scoreThreshold) { break; + } if (parentScore > lastScore) { // Alright! We found a better parent to use. topCandidate = parentOfTopCandidate; @@ -1167,7 +1405,10 @@ Readability.prototype = { // If the top candidate is the only child, use parent instead. This will help sibling // joining logic when adjacent content is actually located in parent's sibling node. parentOfTopCandidate = topCandidate.parentNode; - while (parentOfTopCandidate.tagName != "BODY" && parentOfTopCandidate.children.length == 1) { + while ( + parentOfTopCandidate.tagName != "BODY" && + parentOfTopCandidate.children.length == 1 + ) { topCandidate = parentOfTopCandidate; parentOfTopCandidate = topCandidate.parentNode; } @@ -1180,10 +1421,14 @@ Readability.prototype = { // that might also be related. Things like preambles, content split by ads // that we removed, etc. var articleContent = doc.createElement("DIV"); - if (isPaging) + if (isPaging) { articleContent.id = "readability-content"; + } - var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2); + var siblingScoreThreshold = Math.max( + 10, + topCandidate.readability.contentScore * 0.2 + ); // Keep potential top candidate's parent node to try to get text direction of it later. parentOfTopCandidate = topCandidate.parentNode; var siblings = parentOfTopCandidate.children; @@ -1192,8 +1437,17 @@ Readability.prototype = { var sibling = siblings[s]; var append = false; - this.log("Looking at sibling node:", sibling, sibling.readability ? ("with score " + sibling.readability.contentScore) : ""); - this.log("Sibling has score", sibling.readability ? sibling.readability.contentScore : "Unknown"); + this.log( + "Looking at sibling node:", + sibling, + sibling.readability + ? "with score " + sibling.readability.contentScore + : "" + ); + this.log( + "Sibling has score", + sibling.readability ? sibling.readability.contentScore : "Unknown" + ); if (sibling === topCandidate) { append = true; @@ -1201,11 +1455,18 @@ Readability.prototype = { var contentBonus = 0; // Give a bonus if sibling nodes and top candidates have the example same classname - if (sibling.className === topCandidate.className && topCandidate.className !== "") + if ( + sibling.className === topCandidate.className && + topCandidate.className !== "" + ) { contentBonus += topCandidate.readability.contentScore * 0.2; + } - if (sibling.readability && - ((sibling.readability.contentScore + contentBonus) >= siblingScoreThreshold)) { + if ( + sibling.readability && + sibling.readability.contentScore + contentBonus >= + siblingScoreThreshold + ) { append = true; } else if (sibling.nodeName === "P") { var linkDensity = this._getLinkDensity(sibling); @@ -1214,8 +1475,12 @@ Readability.prototype = { if (nodeLength > 80 && linkDensity < 0.25) { append = true; - } else if (nodeLength < 80 && nodeLength > 0 && linkDensity === 0 && - nodeContent.search(/\.( |$)/) !== -1) { + } else if ( + nodeLength < 80 && + nodeLength > 0 && + linkDensity === 0 && + nodeContent.search(/\.( |$)/) !== -1 + ) { append = true; } } @@ -1224,7 +1489,7 @@ Readability.prototype = { if (append) { this.log("Appending node:", sibling); - if (this.ALTER_TO_DIV_EXCEPTIONS.indexOf(sibling.nodeName) === -1) { + if (!this.ALTER_TO_DIV_EXCEPTIONS.includes(sibling.nodeName)) { // We have a node that isn't a common block level element, like a form or td tag. // Turn it into a div so it doesn't get filtered out later by accident. this.log("Altering sibling:", sibling, "to div."); @@ -1245,12 +1510,14 @@ Readability.prototype = { } } - if (this._debug) + if (this._debug) { this.log("Article content pre-prep: " + articleContent.innerHTML); + } // So we have all of the content that we need. Now we clean it up for presentation. this._prepArticle(articleContent); - if (this._debug) + if (this._debug) { this.log("Article content post-prep: " + articleContent.innerHTML); + } if (neededToCreateTopCandidate) { // We already created a fake div thing, and there wouldn't have been any siblings left @@ -1269,8 +1536,9 @@ Readability.prototype = { articleContent.appendChild(div); } - if (this._debug) + if (this._debug) { this.log("Article content after paging: " + articleContent.innerHTML); + } var parseSuccessful = true; @@ -1282,19 +1550,21 @@ Readability.prototype = { var textLength = this._getInnerText(articleContent, true).length; if (textLength < this._charThreshold) { parseSuccessful = false; + // eslint-disable-next-line no-unsanitized/property page.innerHTML = pageCacheHtml; + this._attempts.push({ + articleContent, + textLength, + }); + if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) { this._removeFlag(this.FLAG_STRIP_UNLIKELYS); - this._attempts.push({articleContent: articleContent, textLength: textLength}); } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) { this._removeFlag(this.FLAG_WEIGHT_CLASSES); - this._attempts.push({articleContent: articleContent, textLength: textLength}); } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) { this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY); - this._attempts.push({articleContent: articleContent, textLength: textLength}); } else { - this._attempts.push({articleContent: articleContent, textLength: textLength}); // No luck after removing flags, just return the longest text we found during the different loops this._attempts.sort(function (a, b) { return b.textLength - a.textLength; @@ -1312,10 +1582,13 @@ Readability.prototype = { if (parseSuccessful) { // Find out text direction from ancestors of final top candidate. - var ancestors = [parentOfTopCandidate, topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate)); - this._someNode(ancestors, function(ancestor) { - if (!ancestor.tagName) + var ancestors = [parentOfTopCandidate, topCandidate].concat( + this._getNodeAncestors(parentOfTopCandidate) + ); + this._someNode(ancestors, function (ancestor) { + if (!ancestor.tagName) { return false; + } var articleDir = ancestor.getAttribute("dir"); if (articleDir) { this._articleDir = articleDir; @@ -1328,40 +1601,32 @@ Readability.prototype = { } }, - /** - * Check whether the input string could be a byline. - * This verifies that the input is a string, and that the length - * is less than 100 chars. - * - * @param possibleByline {string} - a string to check whether its a byline. - * @return Boolean - whether the input string is a byline. - */ - _isValidByline: function(byline) { - if (typeof byline == "string" || byline instanceof String) { - byline = byline.trim(); - return (byline.length > 0) && (byline.length < 100); - } - return false; - }, - /** * Converts some of the common HTML entities in string to their corresponding characters. * * @param str {string} - a string to unescape. * @return string without HTML entity. */ - _unescapeHtmlEntities: function(str) { + _unescapeHtmlEntities(str) { if (!str) { return str; } var htmlEscapeMap = this.HTML_ESCAPE_MAP; - return str.replace(/&(quot|amp|apos|lt|gt);/g, function(_, tag) { - return htmlEscapeMap[tag]; - }).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi, function(_, hex, numStr) { - var num = parseInt(hex || numStr, hex ? 16 : 10); - return String.fromCharCode(num); - }); + return str + .replace(/&(quot|amp|apos|lt|gt);/g, function (_, tag) { + return htmlEscapeMap[tag]; + }) + .replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, numStr) { + var num = parseInt(hex || numStr, hex ? 16 : 10); + + // these character references are replaced by a conforming HTML parser + if (num == 0 || num > 0x10ffff || (num >= 0xd800 && num <= 0xdfff)) { + num = 0xfffd; + } + + return String.fromCodePoint(num); + }); }, /** @@ -1369,29 +1634,51 @@ Readability.prototype = { * For now, only Schema.org objects of type Article or its subtypes are supported. * @return Object with any metadata that could be extracted (possibly none) */ - _getJSONLD: function (doc) { + _getJSONLD(doc) { var scripts = this._getAllNodesWithTag(doc, ["script"]); var metadata; - this._forEachNode(scripts, function(jsonLdElement) { - if (!metadata && jsonLdElement.getAttribute("type") === "application/ld+json") { + this._forEachNode(scripts, function (jsonLdElement) { + if ( + !metadata && + jsonLdElement.getAttribute("type") === "application/ld+json" + ) { try { // Strip CDATA markers if present - var content = jsonLdElement.textContent.replace(/^\s*\s*$/g, ""); + var content = jsonLdElement.textContent.replace( + /^\s*\s*$/g, + "" + ); var parsed = JSON.parse(content); - if ( - !parsed["@context"] || - !parsed["@context"].match(/^https?\:\/\/schema\.org$/) - ) { + + if (Array.isArray(parsed)) { + parsed = parsed.find(it => { + return ( + it["@type"] && + it["@type"].match(this.REGEXPS.jsonLdArticleTypes) + ); + }); + if (!parsed) { + return; + } + } + + var schemaDotOrgRegex = /^https?\:\/\/schema\.org\/?$/; + var matches = + (typeof parsed["@context"] === "string" && + parsed["@context"].match(schemaDotOrgRegex)) || + (typeof parsed["@context"] === "object" && + typeof parsed["@context"]["@vocab"] == "string" && + parsed["@context"]["@vocab"].match(schemaDotOrgRegex)); + + if (!matches) { return; } if (!parsed["@type"] && Array.isArray(parsed["@graph"])) { - parsed = parsed["@graph"].find(function(it) { - return (it["@type"] || "").match( - this.REGEXPS.jsonLdArticleTypes - ); + parsed = parsed["@graph"].find(it => { + return (it["@type"] || "").match(this.REGEXPS.jsonLdArticleTypes); }); } @@ -1405,14 +1692,19 @@ Readability.prototype = { metadata = {}; - if (typeof parsed.name === "string" && typeof parsed.headline === "string" && parsed.name !== parsed.headline) { + if ( + typeof parsed.name === "string" && + typeof parsed.headline === "string" && + parsed.name !== parsed.headline + ) { // we have both name and headline element in the JSON-LD. They should both be the same but some websites like aktualne.cz // put their own name into "name" and the article title to "headline" which confuses Readability. So we try to check if either // "name" or "headline" closely matches the html title, and if so, use that one. If not, then we use "name" by default. var title = this._getArticleTitle(); var nameMatches = this._textSimilarity(parsed.name, title) > 0.75; - var headlineMatches = this._textSimilarity(parsed.headline, title) > 0.75; + var headlineMatches = + this._textSimilarity(parsed.headline, title) > 0.75; if (headlineMatches && !nameMatches) { metadata.title = parsed.headline; @@ -1427,12 +1719,16 @@ Readability.prototype = { if (parsed.author) { if (typeof parsed.author.name === "string") { metadata.byline = parsed.author.name.trim(); - } else if (Array.isArray(parsed.author) && parsed.author[0] && typeof parsed.author[0].name === "string") { + } else if ( + Array.isArray(parsed.author) && + parsed.author[0] && + typeof parsed.author[0].name === "string" + ) { metadata.byline = parsed.author - .filter(function(author) { + .filter(function (author) { return author && typeof author.name === "string"; }) - .map(function(author) { + .map(function (author) { return author.name.trim(); }) .join(", "); @@ -1441,16 +1737,12 @@ Readability.prototype = { if (typeof parsed.description === "string") { metadata.excerpt = parsed.description.trim(); } - if ( - parsed.publisher && - typeof parsed.publisher.name === "string" - ) { + if (parsed.publisher && typeof parsed.publisher.name === "string") { metadata.siteName = parsed.publisher.name.trim(); } if (typeof parsed.datePublished === "string") { metadata.datePublished = parsed.datePublished.trim(); } - return; } catch (err) { this.log(err.message); } @@ -1467,19 +1759,21 @@ Readability.prototype = { * * @return Object with optional "excerpt" and "byline" properties */ - _getArticleMetadata: function(jsonld) { + _getArticleMetadata(jsonld) { var metadata = {}; var values = {}; var metaElements = this._doc.getElementsByTagName("meta"); // property is a space-separated list of values - var propertyPattern = /\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi; + var propertyPattern = + /\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi; // name is a single value - var namePattern = /^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i; + var namePattern = + /^\s*(?:(dc|dcterm|og|twitter|parsely|weibo:(article|webpage))\s*[-\.:]\s*)?(author|creator|pub-date|description|title|site_name)\s*$/i; // Find description tags. - this._forEachNode(metaElements, function(element) { + this._forEachNode(metaElements, function (element) { var elementName = element.getAttribute("name"); var elementProperty = element.getAttribute("property"); var content = element.getAttribute("content"); @@ -1511,42 +1805,56 @@ Readability.prototype = { }); // get title - metadata.title = jsonld.title || - values["dc:title"] || - values["dcterm:title"] || - values["og:title"] || - values["weibo:article:title"] || - values["weibo:webpage:title"] || - values["title"] || - values["twitter:title"]; + metadata.title = + jsonld.title || + values["dc:title"] || + values["dcterm:title"] || + values["og:title"] || + values["weibo:article:title"] || + values["weibo:webpage:title"] || + values.title || + values["twitter:title"] || + values["parsely-title"]; if (!metadata.title) { metadata.title = this._getArticleTitle(); } + const articleAuthor = + typeof values["article:author"] === "string" && + !this._isUrl(values["article:author"]) + ? values["article:author"] + : undefined; + // get author - metadata.byline = jsonld.byline || - values["dc:creator"] || - values["dcterm:creator"] || - values["author"]; + metadata.byline = + jsonld.byline || + values["dc:creator"] || + values["dcterm:creator"] || + values.author || + values["parsely-author"] || + articleAuthor; // get description - metadata.excerpt = jsonld.excerpt || - values["dc:description"] || - values["dcterm:description"] || - values["og:description"] || - values["weibo:article:description"] || - values["weibo:webpage:description"] || - values["description"] || - values["twitter:description"]; + metadata.excerpt = + jsonld.excerpt || + values["dc:description"] || + values["dcterm:description"] || + values["og:description"] || + values["weibo:article:description"] || + values["weibo:webpage:description"] || + values.description || + values["twitter:description"]; // get site name - metadata.siteName = jsonld.siteName || - values["og:site_name"]; + metadata.siteName = jsonld.siteName || values["og:site_name"]; // get article published time - metadata.publishedTime = jsonld.datePublished || - values["article:published_time"] || null; + metadata.publishedTime = + jsonld.datePublished || + values["article:published_time"] || + values["parsely-pub-date"] || + null; // in many sites the meta value is escaped with HTML entities, // so here we need to unescape it @@ -1564,17 +1872,18 @@ Readability.prototype = { * whether as a direct child or as its descendants. * * @param Element - **/ - _isSingleImage: function(node) { - if (node.tagName === "IMG") { - return true; - } - - if (node.children.length !== 1 || node.textContent.trim() !== "") { - return false; + **/ + _isSingleImage(node) { + while (node) { + if (node.tagName === "IMG") { + return true; + } + if (node.children.length !== 1 || node.textContent.trim() !== "") { + return false; + } + node = node.children[0]; } - - return this._isSingleImage(node.children[0]); + return false; }, /** @@ -1584,12 +1893,12 @@ Readability.prototype = { * some sites (e.g. Medium). * * @param Element - **/ - _unwrapNoscriptImages: function(doc) { + **/ + _unwrapNoscriptImages(doc) { // Find img without source or attributes that might contains image, and remove it. // This is done to prevent a placeholder img is replaced by img from noscript in next step. var imgs = Array.from(doc.getElementsByTagName("img")); - this._forEachNode(imgs, function(img) { + this._forEachNode(imgs, function (img) { for (var i = 0; i < img.attributes.length; i++) { var attr = img.attributes[i]; switch (attr.name) { @@ -1605,18 +1914,23 @@ Readability.prototype = { } } - img.parentNode.removeChild(img); + img.remove(); }); // Next find noscript and try to extract its image var noscripts = Array.from(doc.getElementsByTagName("noscript")); - this._forEachNode(noscripts, function(noscript) { + this._forEachNode(noscripts, function (noscript) { // Parse content of noscript and make sure it only contains image - var tmp = doc.createElement("div"); - tmp.innerHTML = noscript.innerHTML; - if (!this._isSingleImage(tmp)) { + if (!this._isSingleImage(noscript)) { return; } + var tmp = doc.createElement("div"); + // We're running in the document context, and using unmodified + // document contents, so doing this should be safe. + // (Also we heavily discourage people from allowing script to + // run at all in this document...) + // eslint-disable-next-line no-unsanitized/property + tmp.innerHTML = noscript.innerHTML; // If noscript has previous sibling and it only contains image, // replace it with noscript content. However we also keep old @@ -1635,7 +1949,11 @@ Readability.prototype = { continue; } - if (attr.name === "src" || attr.name === "srcset" || /\.(jpg|jpeg|png|webp)/i.test(attr.value)) { + if ( + attr.name === "src" || + attr.name === "srcset" || + /\.(jpg|jpeg|png|webp)/i.test(attr.value) + ) { if (newImg.getAttribute(attr.name) === attr.value) { continue; } @@ -1658,8 +1976,8 @@ Readability.prototype = { * Removes script tags from the document. * * @param Element - **/ - _removeScripts: function(doc) { + **/ + _removeScripts(doc) { this._removeNodes(this._getAllNodesWithTag(doc, ["script", "noscript"])); }, @@ -1670,25 +1988,31 @@ Readability.prototype = { * * @param Element * @param string tag of child element - **/ - _hasSingleTagInsideElement: function(element, tag) { + **/ + _hasSingleTagInsideElement(element, tag) { // There should be exactly 1 element child with given tag if (element.children.length != 1 || element.children[0].tagName !== tag) { return false; } // And there should be no text nodes with real content - return !this._someNode(element.childNodes, function(node) { - return node.nodeType === this.TEXT_NODE && - this.REGEXPS.hasContent.test(node.textContent); + return !this._someNode(element.childNodes, function (node) { + return ( + node.nodeType === this.TEXT_NODE && + this.REGEXPS.hasContent.test(node.textContent) + ); }); }, - _isElementWithoutContent: function(node) { - return node.nodeType === this.ELEMENT_NODE && - node.textContent.trim().length == 0 && - (node.children.length == 0 || - node.children.length == node.getElementsByTagName("br").length + node.getElementsByTagName("hr").length); + _isElementWithoutContent(node) { + return ( + node.nodeType === this.ELEMENT_NODE && + !node.textContent.trim().length && + (!node.children.length || + node.children.length == + node.getElementsByTagName("br").length + + node.getElementsByTagName("hr").length) + ); }, /** @@ -1696,26 +2020,36 @@ Readability.prototype = { * * @param Element */ - _hasChildBlockElement: function (element) { - return this._someNode(element.childNodes, function(node) { - return this.DIV_TO_P_ELEMS.has(node.tagName) || - this._hasChildBlockElement(node); + _hasChildBlockElement(element) { + return this._someNode(element.childNodes, function (node) { + return ( + this.DIV_TO_P_ELEMS.has(node.tagName) || + this._hasChildBlockElement(node) + ); }); }, /*** * Determine if a node qualifies as phrasing content. * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content - **/ - _isPhrasingContent: function(node) { - return node.nodeType === this.TEXT_NODE || this.PHRASING_ELEMS.indexOf(node.tagName) !== -1 || - ((node.tagName === "A" || node.tagName === "DEL" || node.tagName === "INS") && - this._everyNode(node.childNodes, this._isPhrasingContent)); + **/ + _isPhrasingContent(node) { + return ( + node.nodeType === this.TEXT_NODE || + this.PHRASING_ELEMS.includes(node.tagName) || + ((node.tagName === "A" || + node.tagName === "DEL" || + node.tagName === "INS") && + this._everyNode(node.childNodes, this._isPhrasingContent)) + ); }, - _isWhitespace: function(node) { - return (node.nodeType === this.TEXT_NODE && node.textContent.trim().length === 0) || - (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR"); + _isWhitespace(node) { + return ( + (node.nodeType === this.TEXT_NODE && + node.textContent.trim().length === 0) || + (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR") + ); }, /** @@ -1725,9 +2059,10 @@ Readability.prototype = { * @param Element * @param Boolean normalizeSpaces (default: true) * @return string - **/ - _getInnerText: function(e, normalizeSpaces) { - normalizeSpaces = (typeof normalizeSpaces === "undefined") ? true : normalizeSpaces; + **/ + _getInnerText(e, normalizeSpaces) { + normalizeSpaces = + typeof normalizeSpaces === "undefined" ? true : normalizeSpaces; var textContent = e.textContent.trim(); if (normalizeSpaces) { @@ -1742,8 +2077,8 @@ Readability.prototype = { * @param Element * @param string - what to split on. Default is "," * @return number (integer) - **/ - _getCharCount: function(e, s) { + **/ + _getCharCount(e, s) { s = s || ","; return this._getInnerText(e).split(s).length - 1; }, @@ -1754,17 +2089,18 @@ Readability.prototype = { * * @param Element * @return void - **/ - _cleanStyles: function(e) { - if (!e || e.tagName.toLowerCase() === "svg") + **/ + _cleanStyles(e) { + if (!e || e.tagName.toLowerCase() === "svg") { return; + } // Remove `style` and deprecated presentational attributes for (var i = 0; i < this.PRESENTATIONAL_ATTRIBUTES.length; i++) { e.removeAttribute(this.PRESENTATIONAL_ATTRIBUTES[i]); } - if (this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.indexOf(e.tagName) !== -1) { + if (this.DEPRECATED_SIZE_ATTRIBUTE_ELEMS.includes(e.tagName)) { e.removeAttribute("width"); e.removeAttribute("height"); } @@ -1782,16 +2118,17 @@ Readability.prototype = { * * @param Element * @return number (float) - **/ - _getLinkDensity: function(element) { + **/ + _getLinkDensity(element) { var textLength = this._getInnerText(element).length; - if (textLength === 0) + if (textLength === 0) { return 0; + } var linkLength = 0; // XXX implement _reduceNodeList? - this._forEachNode(element.getElementsByTagName("a"), function(linkNode) { + this._forEachNode(element.getElementsByTagName("a"), function (linkNode) { var href = linkNode.getAttribute("href"); var coefficient = href && this.REGEXPS.hashUrl.test(href) ? 0.3 : 1; linkLength += this._getInnerText(linkNode).length * coefficient; @@ -1806,29 +2143,34 @@ Readability.prototype = { * * @param Element * @return number (Integer) - **/ - _getClassWeight: function(e) { - if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) + **/ + _getClassWeight(e) { + if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) { return 0; + } var weight = 0; // Look for a special classname - if (typeof(e.className) === "string" && e.className !== "") { - if (this.REGEXPS.negative.test(e.className)) + if (typeof e.className === "string" && e.className !== "") { + if (this.REGEXPS.negative.test(e.className)) { weight -= 25; + } - if (this.REGEXPS.positive.test(e.className)) + if (this.REGEXPS.positive.test(e.className)) { weight += 25; + } } // Look for a special ID - if (typeof(e.id) === "string" && e.id !== "") { - if (this.REGEXPS.negative.test(e.id)) + if (typeof e.id === "string" && e.id !== "") { + if (this.REGEXPS.negative.test(e.id)) { weight -= 25; + } - if (this.REGEXPS.positive.test(e.id)) + if (this.REGEXPS.positive.test(e.id)) { weight += 25; + } } return weight; @@ -1842,10 +2184,10 @@ Readability.prototype = { * @param string tag to clean * @return void **/ - _clean: function(e, tag) { - var isEmbed = ["object", "embed", "iframe"].indexOf(tag) !== -1; + _clean(e, tag) { + var isEmbed = ["object", "embed", "iframe"].includes(tag); - this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(element) { + this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (element) { // Allow youtube and vimeo videos through as people usually want to see those. if (isEmbed) { // First, check the elements attributes to see if any of them contain youtube or vimeo @@ -1856,7 +2198,10 @@ Readability.prototype = { } // For embed with tag, check inner HTML as well. - if (element.tagName === "object" && this._allowedVideoRegex.test(element.innerHTML)) { + if ( + element.tagName === "object" && + this._allowedVideoRegex.test(element.innerHTML) + ) { return false; } } @@ -1874,15 +2219,20 @@ Readability.prototype = { * @param Function filterFn a filter to invoke to determine whether this node 'counts' * @return Boolean */ - _hasAncestorTag: function(node, tagName, maxDepth, filterFn) { + _hasAncestorTag(node, tagName, maxDepth, filterFn) { maxDepth = maxDepth || 3; tagName = tagName.toUpperCase(); var depth = 0; while (node.parentNode) { - if (maxDepth > 0 && depth > maxDepth) + if (maxDepth > 0 && depth > maxDepth) { return false; - if (node.parentNode.tagName === tagName && (!filterFn || filterFn(node.parentNode))) + } + if ( + node.parentNode.tagName === tagName && + (!filterFn || filterFn(node.parentNode)) + ) { return true; + } node = node.parentNode; depth++; } @@ -1892,7 +2242,7 @@ Readability.prototype = { /** * Return an object indicating how many rows and columns this table has. */ - _getRowAndColumnCount: function(table) { + _getRowAndColumnCount(table) { var rows = 0; var columns = 0; var trs = table.getElementsByTagName("tr"); @@ -1901,7 +2251,7 @@ Readability.prototype = { if (rowspan) { rowspan = parseInt(rowspan, 10); } - rows += (rowspan || 1); + rows += rowspan || 1; // Now look for column-related info var columnsInThisRow = 0; @@ -1911,11 +2261,11 @@ Readability.prototype = { if (colspan) { colspan = parseInt(colspan, 10); } - columnsInThisRow += (colspan || 1); + columnsInThisRow += colspan || 1; } columns = Math.max(columns, columnsInThisRow); } - return {rows: rows, columns: columns}; + return { rows, columns }; }, /** @@ -1923,7 +2273,7 @@ Readability.prototype = { * similar checks as * https://searchfox.org/mozilla-central/rev/f82d5c549f046cb64ce5602bfd894b7ae807c8f8/accessible/generic/TableAccessible.cpp#19 */ - _markDataTables: function(root) { + _markDataTables(root) { var tables = root.getElementsByTagName("table"); for (var i = 0; i < tables.length; i++) { var table = tables[i]; @@ -1944,14 +2294,14 @@ Readability.prototype = { } var caption = table.getElementsByTagName("caption")[0]; - if (caption && caption.childNodes.length > 0) { + if (caption && caption.childNodes.length) { table._readabilityDataTable = true; continue; } // If the table has a descendant with any of these tags, consider a data table: var dataTableDescendants = ["col", "colgroup", "tfoot", "thead", "th"]; - var descendantExists = function(tag) { + var descendantExists = function (tag) { return !!table.getElementsByTagName(tag)[0]; }; if (dataTableDescendants.some(descendantExists)) { @@ -1967,6 +2317,13 @@ Readability.prototype = { } var sizeInfo = this._getRowAndColumnCount(table); + + if (sizeInfo.columns == 1 || sizeInfo.rows == 1) { + // single colum/row tables are commonly used for page layout purposes. + table._readabilityDataTable = false; + continue; + } + if (sizeInfo.rows >= 10 || sizeInfo.columns > 4) { table._readabilityDataTable = true; continue; @@ -1977,83 +2334,99 @@ Readability.prototype = { }, /* convert images and figures that have properties like data-src into images that can be loaded without JS */ - _fixLazyImages: function (root) { - this._forEachNode(this._getAllNodesWithTag(root, ["img", "picture", "figure"]), function (elem) { - // In some sites (e.g. Kotaku), they put 1px square image as base64 data uri in the src attribute. - // So, here we check if the data uri is too short, just might as well remove it. - if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) { - // Make sure it's not SVG, because SVG can have a meaningful image in under 133 bytes. - var parts = this.REGEXPS.b64DataUrl.exec(elem.src); - if (parts[1] === "image/svg+xml") { - return; - } - - // Make sure this element has other attributes which contains image. - // If it doesn't, then this src is important and shouldn't be removed. - var srcCouldBeRemoved = false; - for (var i = 0; i < elem.attributes.length; i++) { - var attr = elem.attributes[i]; - if (attr.name === "src") { - continue; + _fixLazyImages(root) { + this._forEachNode( + this._getAllNodesWithTag(root, ["img", "picture", "figure"]), + function (elem) { + // In some sites (e.g. Kotaku), they put 1px square image as base64 data uri in the src attribute. + // So, here we check if the data uri is too short, just might as well remove it. + if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) { + // Make sure it's not SVG, because SVG can have a meaningful image in under 133 bytes. + var parts = this.REGEXPS.b64DataUrl.exec(elem.src); + if (parts[1] === "image/svg+xml") { + return; } - if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) { - srcCouldBeRemoved = true; - break; + // Make sure this element has other attributes which contains image. + // If it doesn't, then this src is important and shouldn't be removed. + var srcCouldBeRemoved = false; + for (var i = 0; i < elem.attributes.length; i++) { + var attr = elem.attributes[i]; + if (attr.name === "src") { + continue; + } + + if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) { + srcCouldBeRemoved = true; + break; + } } - } - // Here we assume if image is less than 100 bytes (or 133B after encoded to base64) - // it will be too small, therefore it might be placeholder image. - if (srcCouldBeRemoved) { - var b64starts = elem.src.search(/base64\s*/i) + 7; - var b64length = elem.src.length - b64starts; - if (b64length < 133) { - elem.removeAttribute("src"); + // Here we assume if image is less than 100 bytes (or 133 after encoded to base64) + // it will be too small, therefore it might be placeholder image. + if (srcCouldBeRemoved) { + var b64starts = parts[0].length; + var b64length = elem.src.length - b64starts; + if (b64length < 133) { + elem.removeAttribute("src"); + } } } - } - - // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580 - if ((elem.src || (elem.srcset && elem.srcset != "null")) && elem.className.toLowerCase().indexOf("lazy") === -1) { - return; - } - for (var j = 0; j < elem.attributes.length; j++) { - attr = elem.attributes[j]; - if (attr.name === "src" || attr.name === "srcset" || attr.name === "alt") { - continue; - } - var copyTo = null; - if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) { - copyTo = "srcset"; - } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) { - copyTo = "src"; + // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580 + if ( + (elem.src || (elem.srcset && elem.srcset != "null")) && + !elem.className.toLowerCase().includes("lazy") + ) { + return; } - if (copyTo) { - //if this is an img or picture, set the attribute directly - if (elem.tagName === "IMG" || elem.tagName === "PICTURE") { - elem.setAttribute(copyTo, attr.value); - } else if (elem.tagName === "FIGURE" && !this._getAllNodesWithTag(elem, ["img", "picture"]).length) { - //if the item is a
that does not contain an image or picture, create one and place it inside the figure - //see the nytimes-3 testcase for an example - var img = this._doc.createElement("img"); - img.setAttribute(copyTo, attr.value); - elem.appendChild(img); + + for (var j = 0; j < elem.attributes.length; j++) { + attr = elem.attributes[j]; + if ( + attr.name === "src" || + attr.name === "srcset" || + attr.name === "alt" + ) { + continue; + } + var copyTo = null; + if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) { + copyTo = "srcset"; + } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) { + copyTo = "src"; + } + if (copyTo) { + //if this is an img or picture, set the attribute directly + if (elem.tagName === "IMG" || elem.tagName === "PICTURE") { + elem.setAttribute(copyTo, attr.value); + } else if ( + elem.tagName === "FIGURE" && + !this._getAllNodesWithTag(elem, ["img", "picture"]).length + ) { + //if the item is a
that does not contain an image or picture, create one and place it inside the figure + //see the nytimes-3 testcase for an example + var img = this._doc.createElement("img"); + img.setAttribute(copyTo, attr.value); + elem.appendChild(img); + } } } } - }); + ); }, - _getTextDensity: function(e, tags) { + _getTextDensity(e, tags) { var textLength = this._getInnerText(e, true).length; if (textLength === 0) { return 0; } var childrenLength = 0; var children = this._getAllNodesWithTag(e, tags); - this._forEachNode(children, (child) => childrenLength += this._getInnerText(child, true).length); + this._forEachNode( + children, + child => (childrenLength += this._getInnerText(child, true).length) + ); return childrenLength / textLength; }, @@ -2063,18 +2436,19 @@ Readability.prototype = { * * @return void **/ - _cleanConditionally: function(e, tag) { - if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) + _cleanConditionally(e, tag) { + if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) { return; + } // Gather counts for other typical elements embedded within. // Traverse backwards so we can remove nodes at the same time // without effecting the traversal. // // TODO: Consider taking into account original contentScore here. - this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(node) { + this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (node) { // First check if this node IS data table, in which case don't remove it. - var isDataTable = function(t) { + var isDataTable = function (t) { return t._readabilityDataTable; }; @@ -2082,7 +2456,10 @@ Readability.prototype = { if (!isList) { var listLength = 0; var listNodes = this._getAllNodesWithTag(node, ["ul", "ol"]); - this._forEachNode(listNodes, (list) => listLength += this._getInnerText(list).length); + this._forEachNode( + listNodes, + list => (listLength += this._getInnerText(list).length) + ); isList = listLength / this._getInnerText(node).length > 0.9; } @@ -2099,6 +2476,15 @@ Readability.prototype = { return false; } + // keep element if it has a data tables + if ( + [...node.getElementsByTagName("table")].some( + tbl => tbl._readabilityDataTable + ) + ) { + return false; + } + var weight = this._getClassWeight(node); this.log("Cleaning Conditionally", node); @@ -2117,10 +2503,21 @@ Readability.prototype = { var img = node.getElementsByTagName("img").length; var li = node.getElementsByTagName("li").length - 100; var input = node.getElementsByTagName("input").length; - var headingDensity = this._getTextDensity(node, ["h1", "h2", "h3", "h4", "h5", "h6"]); + var headingDensity = this._getTextDensity(node, [ + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + ]); var embedCount = 0; - var embeds = this._getAllNodesWithTag(node, ["object", "embed", "iframe"]); + var embeds = this._getAllNodesWithTag(node, [ + "object", + "embed", + "iframe", + ]); for (var i = 0; i < embeds.length; i++) { // If this embed has attribute that matches video regex, don't delete it. @@ -2131,24 +2528,93 @@ Readability.prototype = { } // For embed with tag, check inner HTML as well. - if (embeds[i].tagName === "object" && this._allowedVideoRegex.test(embeds[i].innerHTML)) { + if ( + embeds[i].tagName === "object" && + this._allowedVideoRegex.test(embeds[i].innerHTML) + ) { return false; } embedCount++; } + var innerText = this._getInnerText(node); + + // toss any node whose inner text contains nothing but suspicious words + if ( + this.REGEXPS.adWords.test(innerText) || + this.REGEXPS.loadingWords.test(innerText) + ) { + return true; + } + + var contentLength = innerText.length; var linkDensity = this._getLinkDensity(node); - var contentLength = this._getInnerText(node).length; - - var haveToRemove = - (img > 1 && p / img < 0.5 && !this._hasAncestorTag(node, "figure")) || - (!isList && li > p) || - (input > Math.floor(p/3)) || - (!isList && headingDensity < 0.9 && contentLength < 25 && (img === 0 || img > 2) && !this._hasAncestorTag(node, "figure")) || - (!isList && weight < 25 && linkDensity > 0.2) || - (weight >= 25 && linkDensity > 0.5) || - ((embedCount === 1 && contentLength < 75) || embedCount > 1); + var textishTags = ["SPAN", "LI", "TD"].concat( + Array.from(this.DIV_TO_P_ELEMS) + ); + var textDensity = this._getTextDensity(node, textishTags); + var isFigureChild = this._hasAncestorTag(node, "figure"); + + // apply shadiness checks, then check for exceptions + const shouldRemoveNode = () => { + const errs = []; + if (!isFigureChild && img > 1 && p / img < 0.5) { + errs.push(`Bad p to img ratio (img=${img}, p=${p})`); + } + if (!isList && li > p) { + errs.push(`Too many li's outside of a list. (li=${li} > p=${p})`); + } + if (input > Math.floor(p / 3)) { + errs.push(`Too many inputs per p. (input=${input}, p=${p})`); + } + if ( + !isList && + !isFigureChild && + headingDensity < 0.9 && + contentLength < 25 && + (img === 0 || img > 2) && + linkDensity > 0 + ) { + errs.push( + `Suspiciously short. (headingDensity=${headingDensity}, img=${img}, linkDensity=${linkDensity})` + ); + } + if ( + !isList && + weight < 25 && + linkDensity > 0.2 + this._linkDensityModifier + ) { + errs.push( + `Low weight and a little linky. (linkDensity=${linkDensity})` + ); + } + if (weight >= 25 && linkDensity > 0.5 + this._linkDensityModifier) { + errs.push( + `High weight and mostly links. (linkDensity=${linkDensity})` + ); + } + if ((embedCount === 1 && contentLength < 75) || embedCount > 1) { + errs.push( + `Suspicious embed. (embedCount=${embedCount}, contentLength=${contentLength})` + ); + } + if (img === 0 && textDensity === 0) { + errs.push( + `No useful content. (img=${img}, textDensity=${textDensity})` + ); + } + + if (errs.length) { + this.log("Checks failed", errs); + return true; + } + + return false; + }; + + var haveToRemove = shouldRemoveNode(); + // Allow simple lists of images to remain in pages if (isList && haveToRemove) { for (var x = 0; x < node.children.length; x++) { @@ -2177,7 +2643,7 @@ Readability.prototype = { * @param Function determines whether a node should be removed * @return void **/ - _cleanMatchedNodes: function(e, filter) { + _cleanMatchedNodes(e, filter) { var endOfSearchMarkerNode = this._getNextNode(e, true); var next = this._getNextNode(e); while (next && next != endOfSearchMarkerNode) { @@ -2194,10 +2660,10 @@ Readability.prototype = { * * @param Element * @return void - **/ - _cleanHeaders: function(e) { + **/ + _cleanHeaders(e) { let headingNodes = this._getAllNodesWithTag(e, ["h1", "h2"]); - this._removeNodes(headingNodes, function(node) { + this._removeNodes(headingNodes, function (node) { let shouldRemove = this._getClassWeight(node) < 0; if (shouldRemove) { this.log("Removing header with low class weight:", node); @@ -2213,7 +2679,7 @@ Readability.prototype = { * @param Element the node to check. * @return boolean indicating whether this is a title-like header. */ - _headerDuplicatesTitle: function(node) { + _headerDuplicatesTitle(node) { if (node.tagName != "H1" && node.tagName != "H2") { return false; } @@ -2222,21 +2688,27 @@ Readability.prototype = { return this._textSimilarity(this._articleTitle, heading) > 0.75; }, - _flagIsActive: function(flag) { + _flagIsActive(flag) { return (this._flags & flag) > 0; }, - _removeFlag: function(flag) { + _removeFlag(flag) { this._flags = this._flags & ~flag; }, - _isProbablyVisible: function(node) { - // Have to null-check node.style and node.className.indexOf to deal with SVG and MathML nodes. - return (!node.style || node.style.display != "none") - && (!node.style || node.style.visibility != "hidden") - && !node.hasAttribute("hidden") + _isProbablyVisible(node) { + // Have to null-check node.style and node.className.includes to deal with SVG and MathML nodes. + return ( + (!node.style || node.style.display != "none") && + (!node.style || node.style.visibility != "hidden") && + !node.hasAttribute("hidden") && //check for "fallback-image" so that wikimedia math images are displayed - && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || (node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1)); + (!node.hasAttribute("aria-hidden") || + node.getAttribute("aria-hidden") != "true" || + (node.className && + node.className.includes && + node.className.includes("fallback-image"))) + ); }, /** @@ -2251,12 +2723,14 @@ Readability.prototype = { * * @return void **/ - parse: function () { + parse() { // Avoid parsing too large documents, as per configuration option if (this._maxElemsToParse > 0) { var numTags = this._doc.getElementsByTagName("*").length; if (numTags > this._maxElemsToParse) { - throw new Error("Aborting parsing document; " + numTags + " elements found"); + throw new Error( + "Aborting parsing document; " + numTags + " elements found" + ); } } @@ -2272,11 +2746,13 @@ Readability.prototype = { this._prepDocument(); var metadata = this._getArticleMetadata(jsonLd); + this._metadata = metadata; this._articleTitle = metadata.title; var articleContent = this._grabArticle(); - if (!articleContent) + if (!articleContent) { return null; + } this.log("Grabbed: " + articleContent.innerHTML); @@ -2287,7 +2763,7 @@ Readability.prototype = { // the article's content. if (!metadata.excerpt) { var paragraphs = articleContent.getElementsByTagName("p"); - if (paragraphs.length > 0) { + if (paragraphs.length) { metadata.excerpt = paragraphs[0].textContent.trim(); } } @@ -2299,16 +2775,17 @@ Readability.prototype = { dir: this._articleDir, lang: this._articleLang, content: this._serializer(articleContent), - textContent: textContent, + textContent, length: textContent.length, excerpt: metadata.excerpt, siteName: metadata.siteName || this._articleSiteName, - publishedTime: metadata.publishedTime + publishedTime: metadata.publishedTime, }; - } + }, }; if (typeof module === "object") { + /* eslint-disable-next-line no-redeclare */ /* global module */ module.exports = Readability; } diff --git a/Resources/extract.js b/Resources/extract.js index aef0b64..0a1cbdc 100644 --- a/Resources/extract.js +++ b/Resources/extract.js @@ -10,25 +10,95 @@ function __twoupExtract(html, base) { head.insertBefore(b, head.firstChild); } else { doc = document.cloneNode(true); + if (base && (!doc.baseURI || doc.baseURI === "about:blank")) { + var fallbackHead = doc.head || doc.documentElement; + var fallbackBase = doc.createElement("base"); + fallbackBase.href = base; + fallbackHead.insertBefore(fallbackBase, fallbackHead.firstChild); + } } + // Keep #hash anchor/footnote links relative instead of letting Readability + // rewrite them against baseURI when baseURI != documentURI (e.g. DOMParser docs). + var hashHrefs = null; + if (doc.baseURI && doc.documentURI !== doc.baseURI) { + try { + Object.defineProperty(doc, "documentURI", { + value: doc.baseURI, + configurable: true + }); + } catch (e) {} + } + if (doc.documentURI !== doc.baseURI) { + hashHrefs = Object.create(null); + doc.querySelectorAll("a[href^='#']").forEach(function (a) { + var raw = a.getAttribute("href"); + if (raw && raw.charAt(0) === "#") { + try { + hashHrefs[new URL(raw, doc.baseURI).href] = raw; + } catch (e) {} + } + }); + } + + // Promote lazy-loaded srcsets so responsive images survive extraction. + doc.querySelectorAll("picture source").forEach(function (source) { + var lazySet = source.getAttribute("data-srcset") || + source.getAttribute("data-lazy-srcset") || + source.getAttribute("data-src"); + if (lazySet && !source.getAttribute("srcset")) { + source.setAttribute("srcset", lazySet); + } + }); + // Promote lazy-loaded image sources so they survive extraction. doc.querySelectorAll("img").forEach(function (img) { var src = img.getAttribute("src") || ""; + var isPlaceholder = !src || src.indexOf("data:") === 0 || src === "about:blank"; var lazy = img.getAttribute("data-src") || img.getAttribute("data-lazy-src") || - img.getAttribute("data-original") || img.getAttribute("data-url"); - if (lazy && (!src || src.indexOf("data:") === 0)) img.setAttribute("src", lazy); + img.getAttribute("data-original") || img.getAttribute("data-url") || + img.getAttribute("data-actualsrc") || img.getAttribute("data-hi-res-src"); + if (lazy && isPlaceholder) img.setAttribute("src", lazy); var lazySet = img.getAttribute("data-srcset") || img.getAttribute("data-lazy-srcset"); if (lazySet && !img.getAttribute("srcset")) img.setAttribute("srcset", lazySet); + + // If an inside still lacks a usable src, fall back to its . + var currentSrc = img.getAttribute("src") || ""; + if (!currentSrc || currentSrc.indexOf("data:") === 0 || currentSrc === "about:blank") { + var picture = img.closest && img.closest("picture"); + if (picture) { + var sources = picture.querySelectorAll("source[srcset]"); + for (var i = 0; i < sources.length; i++) { + var firstCandidate = (sources[i].getAttribute("srcset") || "").split(",")[0].trim().split(/\s+/)[0]; + if (firstCandidate && firstCandidate.indexOf("data:") !== 0) { + img.setAttribute("src", firstCandidate); + break; + } + } + } + } }); var article = new Readability(doc).parse(); if (!article) return null; + + var content = article.content || ""; + if (hashHrefs && content) { + var tmp = doc.createElement("div"); + tmp.innerHTML = content; + tmp.querySelectorAll("a[href]").forEach(function (a) { + var href = a.getAttribute("href"); + if (href && hashHrefs[href]) a.setAttribute("href", hashHrefs[href]); + }); + content = tmp.innerHTML; + } + return { title: article.title || "", byline: article.byline || "", site: article.siteName || "", lang: article.lang || "", - content: article.content || "" + dir: article.dir || "", + content: content }; } diff --git a/main.swift b/main.swift index d29d008..c655286 100644 --- a/main.swift +++ b/main.swift @@ -1,7 +1,7 @@ import Cocoa import WebKit -struct Browser { +struct Browser: Sendable { let bundleID: String let name: String let isSafari: Bool @@ -17,21 +17,6 @@ let browsers = [ let safariUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15" -func normalizeURL(_ raw: String) -> URL? { - var text = raw.trimmingCharacters(in: .whitespacesAndNewlines) - if text.isEmpty { return nil } - if !text.contains("://") { text = "https://" + text } - guard let url = URL(string: text), let scheme = url.scheme?.lowercased(), - ["http", "https"].contains(scheme), url.host != nil else { return nil } - return url -} - -func jsonLiteral(_ object: Any) -> String { - guard let data = try? JSONSerialization.data(withJSONObject: object, options: .fragmentsAllowed), - let text = String(data: data, encoding: .utf8) else { return "{}" } - return text.replacingOccurrences(of: " String { guard let url = Bundle.main.url(forResource: name, withExtension: ext), let text = try? String(contentsOf: url, encoding: .utf8) else { @@ -41,35 +26,74 @@ func resourceText(_ name: String, _ ext: String) -> String { return text } +func nsColor(hex: String) -> NSColor { + let cleaned = hex.trimmingCharacters(in: CharacterSet(charactersIn: "#")) + guard cleaned.count == 6, let value = UInt32(cleaned, radix: 16) else { + return .windowBackgroundColor + } + let r = CGFloat((value >> 16) & 0xff) / 255.0 + let g = CGFloat((value >> 8) & 0xff) / 255.0 + let b = CGFloat(value & 0xff) / 255.0 + return NSColor(srgbRed: r, green: g, blue: b, alpha: 1.0) +} + // MARK: Readwise Reader +@MainActor enum Keychain { - static let base: [String: Any] = [ - kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: "com.mclemore.twoup", - kSecAttrAccount as String: "readwise", - ] + private static func baseQuery() -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: "com.mclemore.twoup", + kSecAttrAccount as String: "readwise", + ] + } + static func get() -> String? { - var query = base + var query = baseQuery() query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne var out: CFTypeRef? - guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil } + guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, + let data = out as? Data else { return nil } return String(data: data, encoding: .utf8) } - static func set(_ value: String) { - SecItemDelete(base as CFDictionary) - var query = base + + @discardableResult + static func set(_ value: String) -> Bool { + let deleteStatus = SecItemDelete(baseQuery() as CFDictionary) + if deleteStatus != errSecSuccess && deleteStatus != errSecItemNotFound { + NSLog("TwoUp: Keychain delete before save returned OSStatus %d", deleteStatus) + } + var query = baseQuery() query[kSecValueData as String] = Data(value.utf8) - SecItemAdd(query as CFDictionary, nil) + query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + let status = SecItemAdd(query as CFDictionary, nil) + if status != errSecSuccess { + NSLog("TwoUp: Keychain save failed with OSStatus %d", status) + return false + } + return true + } + + static func delete() { + let status = SecItemDelete(baseQuery() as CFDictionary) + if status != errSecSuccess && status != errSecItemNotFound { + NSLog("TwoUp: Keychain delete failed with OSStatus %d", status) + } } - static func delete() { SecItemDelete(base as CFDictionary) } } struct ReadwiseError: LocalizedError { let errorDescription: String? } -func readwiseRequest(_ url: URL, method: String = "GET", body: [String: Any]? = nil, token: String, - completion: @escaping (Result<[String: Any], Error>) -> Void) { +@MainActor +func readwiseRequest( + _ url: URL, + method: String = "GET", + body: [String: Any]? = nil, + token: String, + completion: @escaping @MainActor (Result<[String: Any], Error>) -> Void +) { var request = URLRequest(url: url) request.httpMethod = method request.setValue("Token \(token)", forHTTPHeaderField: "Authorization") @@ -77,36 +101,28 @@ func readwiseRequest(_ url: URL, method: String = "GET", body: [String: Any]? = request.httpBody = try? JSONSerialization.data(withJSONObject: body) request.setValue("application/json", forHTTPHeaderField: "Content-Type") } - URLSession.shared.dataTask(with: request) { data, response, error in - let http = response as? HTTPURLResponse - let status = http?.statusCode ?? 0 + Task { @MainActor in let result: Result<[String: Any], Error> - if let error { + do { + let (data, response) = try await URLSession.shared.data(for: request) + let http = response as? HTTPURLResponse + let status = http?.statusCode ?? 0 + if status == 401 || status == 403 { + result = .failure(ReadwiseError(errorDescription: "Readwise rejected the token. Reconnect with a fresh one.")) + } else if status == 429 { + let wait = http?.value(forHTTPHeaderField: "Retry-After") ?? "a few" + result = .failure(ReadwiseError(errorDescription: "Readwise rate limit hit. Try again in \(wait) seconds.")) + } else if !(200..<300).contains(status) { + result = .failure(ReadwiseError(errorDescription: "Readwise returned HTTP \(status).")) + } else { + let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + result = .success(object ?? [:]) + } + } catch { result = .failure(error) - } else if status == 401 || status == 403 { - result = .failure(ReadwiseError(errorDescription: "Readwise rejected the token. Reconnect with a fresh one.")) - } else if status == 429 { - let wait = http?.value(forHTTPHeaderField: "Retry-After") ?? "a few" - result = .failure(ReadwiseError(errorDescription: "Readwise rate limit hit. Try again in \(wait) seconds.")) - } else if !(200..<300).contains(status) { - result = .failure(ReadwiseError(errorDescription: "Readwise returned HTTP \(status).")) - } else { - let object = data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any] - result = .success(object ?? [:]) } - DispatchQueue.main.async { completion(result) } - }.resume() -} - -// Keeps only readable top-level documents (no highlights, notes, PDFs, videos). -func slimDoc(_ doc: [String: Any]) -> [String: Any]? { - guard let id = doc["id"] as? String, doc["parent_id"] == nil || doc["parent_id"] is NSNull, - ["article", "email", "rss"].contains(doc["category"] as? String ?? "") else { return nil } - var out: [String: Any] = ["id": id] - for key in ["title", "author", "site_name", "source_url", "word_count", "reading_progress"] { - if let value = doc[key], !(value is NSNull) { out[key] = value } + completion(result) } - return out } struct QueueCache { @@ -114,6 +130,28 @@ struct QueueCache { var fetchedAt: Date } +struct PendingLoad { + let token: Int + let url: URL + let html: String? + var isExtracting = false +} + +enum BrowserTabGrabResult: Sendable { + case success(url: URL, html: String?) + case failure(String) +} + +@MainActor +final class WeakScriptMessageHandler: NSObject, WKScriptMessageHandler { + weak var target: WKScriptMessageHandler? + init(_ target: WKScriptMessageHandler) { self.target = target } + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + target?.userContentController(userContentController, didReceive: message) + } +} + +@MainActor final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNavigationDelegate, WKScriptMessageHandler { var window: NSWindow! var reader: WKWebView! @@ -122,17 +160,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa var template = "" var extractorSource = "" var lastBrowserID: String? + var workspaceObserver: NSObjectProtocol? var launchURL: URL? var currentURL: URL? - var pending: (token: Int, url: URL, html: String?)? + var pending: PendingLoad? var token = 0 - var extracting = Set() + var expectingReaderLoad = false + var expectedReaderBaseURL: URL? var currentDocID: String? var archivingDocIDs = Set() var showingQueue = false var queueLocation = "later" var queueCache: [String: QueueCache] = [:] var queueRevision = 0 + var queueFetchToken = 0 + + private let preferFullScreenKey = "preferFullScreen" // MARK: Launch @@ -141,18 +184,24 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa browsers.contains(where: { $0.bundleID == front }) { lastBrowserID = front } - NSWorkspace.shared.notificationCenter.addObserver( + workspaceObserver = NSWorkspace.shared.notificationCenter.addObserver( forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main ) { [weak self] note in guard let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication, let id = app.bundleIdentifier, browsers.contains(where: { $0.bundleID == id }) else { return } - self?.lastBrowserID = id + Task { @MainActor [weak self] in + self?.lastBrowserID = id + } } } func applicationDidFinishLaunching(_ notification: Notification) { template = resourceText("reader", "html") extractorSource = resourceText("Readability", "js") + "\n" + resourceText("extract", "js") + "\ntrue;" + let savedPrefs = prefs() + if let savedLoc = savedPrefs["queueLocation"] as? String, !savedLoc.isEmpty { + queueLocation = savedLoc + } buildMenu() let screen = NSScreen.main?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1440, height: 900) @@ -163,33 +212,43 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa window.title = "TwoUp" window.titleVisibility = .hidden window.titlebarAppearsTransparent = true + window.minSize = NSSize(width: 640, height: 480) window.collectionBehavior.insert(.fullScreenPrimary) window.isReleasedWhenClosed = false window.delegate = self + window.setFrameAutosaveName("TwoUpMainWindow") + syncWindowAppearance(theme: savedPrefs["theme"] as? String) let bounds = window.contentView!.bounds let loaderConfig = WKWebViewConfiguration() + loaderConfig.websiteDataStore = .nonPersistent() loaderConfig.mediaTypesRequiringUserActionForPlayback = .all loader = WKWebView(frame: bounds, configuration: loaderConfig) loader.customUserAgent = safariUserAgent loader.navigationDelegate = self loader.autoresizingMask = [.width, .height] + loader.setValue(false, forKey: "drawsBackground") let readerConfig = WKWebViewConfiguration() - readerConfig.userContentController.add(self, name: "twoup") + readerConfig.userContentController.add(WeakScriptMessageHandler(self), name: "twoup") reader = WKWebView(frame: bounds, configuration: readerConfig) reader.navigationDelegate = self reader.autoresizingMask = [.width, .height] + reader.setValue(false, forKey: "drawsBackground") window.contentView!.addSubview(loader) window.contentView!.addSubview(reader) window.makeKeyAndOrderFront(nil) window.makeFirstResponder(reader) NSApp.activate(ignoringOtherApps: true) - window.toggleFullScreen(nil) - let args = CommandLine.arguments.dropFirst().filter { !$0.hasPrefix("-") } - if let url = launchURL ?? args.first.flatMap(normalizeURL) { + let preferFullScreen = UserDefaults.standard.object(forKey: preferFullScreenKey) as? Bool ?? true + if preferFullScreen && !window.styleMask.contains(.fullScreen) { + window.toggleFullScreen(nil) + } + + let cliURL = parseLaunchURL(arguments: Array(CommandLine.arguments.dropFirst())) + if let url = launchURL ?? cliURL { open(url, html: nil) } else if lastBrowserID != nil { grabBrowserTab() @@ -199,12 +258,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa } func application(_ application: NSApplication, open urls: [URL]) { - guard let url = urls.first(where: { ["http", "https"].contains($0.scheme?.lowercased() ?? "") }) else { return } + guard let url = urls.first(where: { ["http", "https"].contains($0.scheme?.lowercased() ?? "") && !($0.host ?? "").isEmpty }) else { return } if reader == nil { launchURL = url } else { open(url, html: nil) } } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } + func applicationWillTerminate(_ notification: Notification) { + reader?.configuration.userContentController.removeScriptMessageHandler(forName: "twoup") + if let observer = workspaceObserver { + NSWorkspace.shared.notificationCenter.removeObserver(observer) + workspaceObserver = nil + } + } + + func windowDidEnterFullScreen(_ notification: Notification) { + UserDefaults.standard.set(true, forKey: preferFullScreenKey) + } + + func windowDidExitFullScreen(_ notification: Notification) { + UserDefaults.standard.set(false, forKey: preferFullScreenKey) + } + // MARK: Menu func buildMenu() { @@ -244,14 +319,31 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa item("Select All", #selector(NSText.selectAll(_:)), "a"), ]) submenu("View", [ + item("Zoom In", #selector(zoomInAction), "+"), + item("Zoom Out", #selector(zoomOutAction), "-"), + item("Actual Size", #selector(zoomResetAction), "0"), + .separator(), item("Toggle Full Screen", #selector(NSWindow.toggleFullScreen(_:)), "f", [.command, .control]), ]) NSApp.mainMenu = main } - @objc func openURLAction() { showStart() } + @objc func openURLAction() { showStart(focusUrl: true) } @objc func grabAction() { grabBrowserTab() } - @objc func originalAction() { if let url = currentURL { NSWorkspace.shared.open(url) } } + @objc func originalAction() { + if let url = currentURL, isAllowedExternalURL(url) { + NSWorkspace.shared.open(url) + } + } + @objc func zoomInAction() { + reader.evaluateJavaScript("window.twoupZoom && window.twoupZoom(1)") + } + @objc func zoomOutAction() { + reader.evaluateJavaScript("window.twoupZoom && window.twoupZoom(-1)") + } + @objc func zoomResetAction() { + reader.evaluateJavaScript("window.twoupZoom && window.twoupZoom(0)") + } // MARK: Screens @@ -259,24 +351,44 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa UserDefaults.standard.dictionary(forKey: "prefs") ?? [:] } - func render(_ mode: String, article: [String: Any]? = nil, url: URL? = nil, message: String? = nil) { + func syncWindowAppearance(theme: String?) { + let spec = themeWindowAppearance(theme: theme) + if let isDark = spec.isDark { + window.appearance = NSAppearance(named: isDark ? .darkAqua : .aqua) + window.backgroundColor = nsColor(hex: spec.bgHex) + } else { + window.appearance = nil + let systemDark = window.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua + window.backgroundColor = nsColor(hex: systemDark ? "#161616" : spec.bgHex) + } + } + + func render(_ mode: String, article: [String: Any]? = nil, url: URL? = nil, message: String? = nil, focusUrl: Bool = false) { showingQueue = mode == "start" || mode == "error" var data: [String: Any] = ["mode": mode, "prefs": prefs()] if let article { data["article"] = article } if let url { data["url"] = url.absoluteString } if let message { data["message"] = message } - if mode == "article", let currentDocID { data["docId"] = currentDocID } + if focusUrl { data["focusUrl"] = true } + if mode == "article" { + if let currentDocID { data["docId"] = currentDocID } + if let dir = article?["dir"] as? String, !dir.isEmpty { data["dir"] = dir } + } let html = template.replacingOccurrences(of: "/*__TWOUP_DATA__*/", with: "window.TWOUP = \(jsonLiteral(data));") - reader.loadHTMLString(html, baseURL: mode == "article" ? url : nil) + let baseURL = mode == "article" ? url : nil + expectingReaderLoad = true + expectedReaderBaseURL = baseURL + reader.loadHTMLString(html, baseURL: baseURL) window.makeFirstResponder(reader) } - func showStart(message: String? = nil, url: URL? = nil, notice: String? = nil) { + func showStart(message: String? = nil, url: URL? = nil, notice: String? = nil, focusUrl: Bool = false) { token += 1 pending = nil currentDocID = nil + stopLoader() window.title = "TwoUp" - render(message == nil ? "start" : "error", url: url, message: message ?? notice) + render(message == nil ? "start" : "error", url: url, message: message ?? notice, focusUrl: focusUrl) } // MARK: Loading and extraction @@ -284,7 +396,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa func open(_ url: URL, html: String?, docID: String? = nil) { token += 1 let t = token - pending = (t, url, html) + pending = PendingLoad(token: t, url: url, html: html) currentURL = url currentDocID = docID render("loading", url: url) @@ -294,20 +406,34 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa loader.load(URLRequest(url: url)) } // Slow or never-finishing pages: extract whatever has loaded. - DispatchQueue.main.asyncAfter(deadline: .now() + 20) { self.extract(token: t) } + Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: 20_000_000_000) + self?.extract(token: t) + } } func extract(token t: Int) { - guard let p = pending, p.token == t, !extracting.contains(t) else { return } - extracting.insert(t) + guard var p = pending, p.token == t, !p.isExtracting else { return } + p.isExtracting = true + pending = p let base = (p.html == nil ? loader.url : nil) ?? p.url - loader.evaluateJavaScript(extractorSource, in: nil, in: .defaultClient) { _ in + guard !extractorSource.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + fail("TwoUp is missing its article extractor resources.", url: base) + return + } + loader.evaluateJavaScript(extractorSource, in: nil, in: .defaultClient) { [weak self] injectResult in + guard let self, self.pending?.token == t else { return } + if case .failure(let error) = injectResult { + NSLog("TwoUp: extractor script evaluation failed: %@", error.localizedDescription) + self.fail("Couldn't read that page (\(error.localizedDescription)).", url: base) + return + } self.loader.callAsyncJavaScript( "return __twoupExtract(html, base);", arguments: ["html": p.html ?? NSNull(), "base": base.absoluteString], in: nil, in: .defaultClient - ) { result in - guard self.pending?.token == t else { return } + ) { [weak self] result in + guard let self, self.pending?.token == t else { return } switch result { case .success(let value): if let article = value as? [String: Any], let content = article["content"] as? String, !content.isEmpty { @@ -328,7 +454,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa func fail(_ message: String, url: URL) { showStart(message: message, url: url) - stopLoader() } func stopLoader() { @@ -358,16 +483,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa } else { pushQueue(["state": "loading", "location": location, "items": []]) } - fetchQueue(location, key: key, cursor: nil, items: [], pagesLeft: 3) + queueFetchToken += 1 + fetchQueue(location, key: key, cursor: nil, items: [], pagesLeft: 3, fetchToken: queueFetchToken) } - func fetchQueue(_ location: String, key: String, cursor: String?, items: [[String: Any]], pagesLeft: Int) { + func fetchQueue(_ location: String, key: String, cursor: String?, items: [[String: Any]], pagesLeft: Int, fetchToken: Int) { let revision = queueRevision - var components = URLComponents(string: "https://readwise.io/api/v3/list/")! - components.queryItems = [URLQueryItem(name: "location", value: location)] - + (cursor.map { [URLQueryItem(name: "pageCursor", value: $0)] } ?? []) - readwiseRequest(components.url!, token: key) { result in - guard self.queueRevision == revision else { return } + var queryItems = [URLQueryItem(name: "location", value: location)] + if let cursor { + queryItems.append(URLQueryItem(name: "pageCursor", value: cursor)) + } + guard let url = readwiseEndpointURL(path: "/api/v3/list/", queryItems: queryItems) else { + pushQueue(["state": "error", "location": location, "message": "Invalid Readwise queue request.", + "items": queueCache[location]?.items ?? []]) + return + } + readwiseRequest(url, token: key) { [weak self] result in + guard let self, self.queueRevision == revision, self.queueFetchToken == fetchToken else { return } switch result { case .failure(let error): self.pushQueue(["state": "error", "location": location, "message": error.localizedDescription, @@ -375,7 +507,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa case .success(let json): let all = items + (json["results"] as? [[String: Any]] ?? []).compactMap(slimDoc) if let next = json["nextPageCursor"] as? String, pagesLeft > 1 { - self.fetchQueue(location, key: key, cursor: next, items: all, pagesLeft: pagesLeft - 1) + self.fetchQueue(location, key: key, cursor: next, items: all, pagesLeft: pagesLeft - 1, fetchToken: fetchToken) return } self.queueCache[location] = QueueCache(items: all, fetchedAt: Date()) @@ -392,13 +524,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa let t = token pending = nil currentDocID = nil + stopLoader() let item = queueCache.values.flatMap(\.items).first { $0["id"] as? String == id } let listedURL = (item?["source_url"] as? String).flatMap(normalizeURL) render("loading", url: listedURL) - var components = URLComponents(string: "https://readwise.io/api/v3/list/")! - components.queryItems = [URLQueryItem(name: "id", value: id), URLQueryItem(name: "withHtmlContent", value: "true")] - readwiseRequest(components.url!, token: key) { result in - guard self.token == t else { return } + guard let url = readwiseEndpointURL(path: "/api/v3/list/", queryItems: [ + URLQueryItem(name: "id", value: id), + URLQueryItem(name: "withHtmlContent", value: "true"), + ]) else { + showStart(message: "Invalid Readwise document request.") + return + } + readwiseRequest(url, token: key) { [weak self] result in + guard let self, self.token == t else { return } switch result { case .failure(let error): self.showStart(message: error.localizedDescription) @@ -418,8 +556,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa self.currentURL = url self.window.title = text("title").isEmpty ? "TwoUp" : text("title") self.render("article", - article: ["title": text("title"), "byline": text("author"), "site": text("site_name"), "content": html], - url: url ?? URL(string: "https://read.readwise.io")!) + article: [ + "title": text("title"), + "byline": text("author"), + "site": text("site_name"), + "dir": text("dir"), + "content": html, + ], + url: url ?? readwiseReaderBaseURL()) } } } @@ -430,14 +574,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa archiveFailed(id, message: "Connect Readwise Reader from the queue, then try again.") return } + guard let url = readwiseUpdateURL(docID: id) else { + archiveFailed(id, message: "Invalid Readwise document ID.") + return + } archivingDocIDs.insert(id) var update: [String: Any] = ["location": "archive"] if markRead { update["reading_progress"] = 1 update["seen"] = true } - readwiseRequest(URL(string: "https://readwise.io/api/v3/update/\(id)/")!, method: "PATCH", - body: update, token: key) { result in + readwiseRequest(url, method: "PATCH", body: update, token: key) { [weak self] result in + guard let self else { return } self.archivingDocIDs.remove(id) switch result { case .failure(let error): @@ -447,6 +595,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa case .success: // A list response started before the archive could still contain this document. self.queueRevision += 1 + self.queueFetchToken += 1 for location in self.queueCache.keys { self.queueCache[location]?.items.removeAll { $0["id"] as? String == id } } @@ -461,13 +610,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa func connectReadwise(_ raw: String) { let key = raw.trimmingCharacters(in: .whitespacesAndNewlines) - readwiseRequest(URL(string: "https://readwise.io/api/v2/auth/")!, token: key) { result in + guard let url = readwiseEndpointURL(path: "/api/v2/auth/") else { + pushQueue(["state": "needsToken", "message": "Invalid Readwise auth endpoint."]) + return + } + readwiseRequest(url, token: key) { [weak self] result in + guard let self else { return } switch result { case .success: - Keychain.set(key) - self.queueCache = [:] - self.queueRevision += 1 - self.serveQueue(force: true) + if Keychain.set(key) { + self.queueCache = [:] + self.queueRevision += 1 + self.queueFetchToken += 1 + self.serveQueue(force: true) + } else { + self.pushQueue(["state": "needsToken", "message": "Couldn't save the token to your macOS Keychain."]) + } case .failure(let error): self.pushQueue(["state": "needsToken", "message": error.localizedDescription]) } @@ -483,6 +641,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa showStart(message: "No supported browser is running (Safari, Chrome, Arc, Brave, Edge).") return } + token += 1 + let t = token + pending = nil + currentDocID = nil + stopLoader() + render("loading") + + Task.detached(priority: .userInitiated) { + let outcome = Self.runBrowserAppleScript(for: browser) + await MainActor.run { [weak self] in + guard let self, self.token == t else { return } + switch outcome { + case .success(let url, let html): + self.open(url, html: html) + case .failure(let reason): + self.showStart(message: reason) + } + } + } + } + + nonisolated private static func runBrowserAppleScript(for browser: Browser) -> BrowserTabGrabResult { let target = "tell application id \"\(browser.bundleID)\"" let tab = browser.isSafari ? "front document" : "active tab of front window" var error: NSDictionary? @@ -492,8 +672,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa let reason = code == -1743 ? "TwoUp isn't allowed to control \(browser.name). Turn it on in System Settings → Privacy & Security → Automation." : "Couldn't read the current tab in \(browser.name)." - showStart(message: reason) - return + return .failure(reason) } // The page's own HTML keeps logged-in/paywalled content. Needs the browser's // "Allow JavaScript from Apple Events" setting; otherwise we load the URL fresh. @@ -503,15 +682,32 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa : "\(target) to execute active tab of front window javascript \"\(js)\"" var htmlError: NSDictionary? let html = NSAppleScript(source: htmlScript)?.executeAndReturnError(&htmlError).stringValue - open(url, html: (html?.count ?? 0) > 500 ? html : nil) + if let htmlError { + NSLog("TwoUp: browser HTML AppleScript unavailable for %@: %@", browser.name, htmlError) + } + return .success(url: url, html: (html?.count ?? 0) > 500 ? html : nil) } // MARK: WKNavigationDelegate func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, - decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { - if webView === reader, action.navigationType == .linkActivated, let url = action.request.url { - NSWorkspace.shared.open(url) + decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) { + if webView === reader { + if action.navigationType == .linkActivated { + if let url = action.request.url, isAllowedExternalURL(url) { + NSWorkspace.shared.open(url) + } + decisionHandler(.cancel) + return + } + if action.navigationType == .other, + action.targetFrame?.isMainFrame ?? true, + expectingReaderLoad, + matchesExpectedReaderURL(action.request.url, expected: expectedReaderBaseURL) { + expectingReaderLoad = false + decisionHandler(.allow) + return + } decisionHandler(.cancel) return } @@ -523,18 +719,38 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + if webView === reader { + expectingReaderLoad = false + return + } guard webView === loader, let p = pending else { return } // Give script-rendered pages a moment to settle. - let delay = p.html == nil ? 0.8 : 0 - DispatchQueue.main.asyncAfter(deadline: .now() + delay) { self.extract(token: p.token) } + let delayNs: UInt64 = p.html == nil ? 800_000_000 : 0 + let expectedToken = p.token + if delayNs == 0 { + extract(token: expectedToken) + } else { + Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: delayNs) + self?.extract(token: expectedToken) + } + } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { + if webView === reader { + expectingReaderLoad = false + return + } guard webView === loader, let p = pending else { return } extract(token: p.token) } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { + if webView === reader { + expectingReaderLoad = false + return + } guard webView === loader, let p = pending else { return } if (error as NSError).code == NSURLErrorCancelled { return } fail("Couldn't load the page: \(error.localizedDescription)", url: p.url) @@ -543,7 +759,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa // MARK: Messages from the reader page func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { - guard let body = message.body as? [String: Any], let type = body["type"] as? String else { return } + guard message.webView === reader, + message.frameInfo.isMainFrame, + let body = message.body as? [String: Any], + let type = body["type"] as? String else { return } switch type { case "open": if let text = body["url"] as? String { @@ -552,7 +771,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa case "grab": grabBrowserTab() case "original": originalAction() case "prefs": - if let p = body["prefs"] as? [String: Any] { UserDefaults.standard.set(p, forKey: "prefs") } + if let p = body["prefs"] as? [String: Any] { + UserDefaults.standard.set(p, forKey: "prefs") + syncWindowAppearance(theme: p["theme"] as? String) + } case "queue": if let location = body["location"] as? String { queueLocation = location } serveQueue(force: body["force"] as? Bool ?? false) @@ -567,6 +789,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa Keychain.delete() queueCache = [:] queueRevision += 1 + queueFetchToken += 1 pushQueue(["state": "needsToken"]) case "exitFullscreen": if window.styleMask.contains(.fullScreen) { window.toggleFullScreen(nil) } @@ -575,8 +798,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNa } } -let app = NSApplication.shared -let delegate = AppDelegate() -app.delegate = delegate -app.setActivationPolicy(.regular) -app.run() +MainActor.assumeIsolated { + let app = NSApplication.shared + let delegate = AppDelegate() + app.delegate = delegate + app.setActivationPolicy(.regular) + withExtendedLifetime(delegate) { + app.run() + } +}