Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support startpage.com #19

Merged
merged 2 commits into from
Nov 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -244,5 +244,21 @@
"options_addSubscriptionDialog_addButton": {
"message": "Add",
"description": "The text of the add button on the add-subscription dialog."
},
"options_extraSiteSupportTitle": {
"message": "Extra site support",
"description": "The title of the extra-site-support section."
},
"options_extraSiteSupportDescription": {
"message": "You can enable these site supporting below. Please notice this will require the user permission to access the site you enabled",
"description": "The title of the extra-site-support section."
},
"options_enableSite": {
"message": "Enable",
"description": "The text of enable extra site support"
},
"options_enabled": {
"message": "Enabled",
"description": "The text for site already enabled"
}
}
13 changes: 13 additions & 0 deletions src/_locales/zh_TW/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -184,5 +184,18 @@
},
"options_addSubscriptionDialog_addButton": {
"message": "Add"
},
"options_extraSiteSupportTitle": {
"message": "支援額外的網站"
},
"options_extraSiteSupportDescription": {
"message": "你可以開啟以下網站的支援,請注意你必須允許此擴充功能存取你要支援的網站"
},
"options_enableSite": {
"message": "啟用",
"description": "The text of enable extra site support"
},
"options_enabled": {
"message": "已啟用"
}
}
29 changes: 29 additions & 0 deletions src/options.html
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,35 @@ <h1 class="title">
</li>
</ul>
</section>
<section id="extraSiteSupport" class="section">
<h1 class="title">
<span data-i18n="options_extraSiteSupportTitle"></span>
</h1>
<ul class="list">
<li class="list-item">
<p class="has-text-grey">
<span data-i18n="options_extraSiteSupportDescription"></span>
</p>
</li>
<li class="list-item">
<div class="columns is-vcentered">
<div class="column">
<label for="startpageSupport">
<span>startpage.com</span>
</label>
</div>
<div class="column is-narrow">
<button id="startpageSupport" class="button has-text-primary">
<span data-i18n="options_enableSite"></span>
</button>
<button id="startpageSupportOn" disabled class="button is-hidden is-success is-disabled">
<span data-i18n="options_enabled"></span>
</button>
</div>
</div>
</li>
</ul>
</section>
<section id="syncSection" class="section">
<h1 class="title">
<span data-i18n="options_syncTitle"></span>
Expand Down
117 changes: 117 additions & 0 deletions src/ts/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
sendMessage,
addMessageListener,
BackgroundPage,
SiteID,
} from './common';

const backgroundPage = (window as Window) as BackgroundPage;
Expand Down Expand Up @@ -438,12 +439,128 @@ backgroundPage.removeCachedAuthToken = async function(token: string): Promise<vo

// #endregion Auth

// #region Extra Site

interface SiteInfo {
baseUrl: string;
matches: string[];
registration?: browser.contentScripts.RegisteredContentScript;
}

interface ExtraSiteInfo {
startpage: SiteInfo;
}

const EXTRA_SITE_INFO: ExtraSiteInfo = {
startpage: {
baseUrl: 'https://www.startpage.com',
matches: [
'https://www.startpage.com/do/search',
'https://www.startpage.com/rvd/search',
'https://www.startpage.com/sp/search',
],
},
};

async function wasPreviouslyLoaded(tabId: number, loadCheck: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject): void => {
chrome.tabs.executeScript(
tabId,
{ code: loadCheck, runAt: 'document_start' },
(result): void => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
return;
}

resolve(result && result[0]);
},
);
});
}

function checkSiteAccess(url: string, request = false): Promise<boolean> {
const method = request ? 'request' : 'contains';
return new Promise<boolean>((resolve, reject) => {
const u = new URL(url);
chrome.permissions[method]({ origins: [`${u.protocol}//${u.hostname}/*`] }, granted => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
} else {
resolve(granted);
}
});
});
}

// #if BROWSER === 'chrome'
chrome.tabs.onUpdated.addListener((tabId, { status }): void => {
if (status !== 'loading') {
return;
}

chrome.tabs.get(
tabId,
async (tab): Promise<void> => {
const loadCheck = `window['__UBLACKLIST_CONTENT_SCRIPT_DYNAMIC_INJECTED__']`;

if (!tab.url || !(await checkSiteAccess(tab.url)) || !wasPreviouslyLoaded(tabId, loadCheck)) {
return;
}
for (const { matches } of Object.values(EXTRA_SITE_INFO)) {
for (const url of matches) {
if (tab.url.startsWith(url)) {
chrome.tabs.insertCSS({ file: 'css/content.css', runAt: 'document_start' });
chrome.tabs.executeScript({ file: 'js/content.js', runAt: 'document_start' });
chrome.tabs.executeScript({ code: `${loadCheck}=true`, runAt: 'document_start' });
}
}
}
},
);
});
// #endif

backgroundPage.hasSiteEnable = function(site: SiteID): Promise<boolean> {
return checkSiteAccess(EXTRA_SITE_INFO[site].baseUrl);
};

backgroundPage.enableSite = async function(site: SiteID): Promise<void> {
// #if BROWSER === 'firefox'
const info = EXTRA_SITE_INFO[site];
if (info.registration) {
await info.registration.unregister();
}

EXTRA_SITE_INFO[site].registration = await chrome.contentScripts.register({
css: [{ file: 'css/content.css' }],
js: [{ file: 'js/content.js' }],
runAt: 'document_start',
matches: EXTRA_SITE_INFO[site].matches,
});
// #endif
};

backgroundPage.requestEnableSite = function(site: SiteID): Promise<boolean> {
return checkSiteAccess(EXTRA_SITE_INFO[site].baseUrl, true).then(async granted => {
if (granted) {
await backgroundPage.enableSite(site);
}
return granted;
});
};

// #endregion Extra Site

async function main(): Promise<void> {
addMessageListener('setBlacklist', ({ blacklist }) => {
backgroundPage.setBlacklist(blacklist);
});

const { syncInterval, updateInterval } = await getOptions('syncInterval', 'updateInterval');
if (await backgroundPage.hasSiteEnable('startpage')) {
await backgroundPage.enableSite('startpage');
}
backgroundPage.syncBlacklist();
setInterval(() => {
backgroundPage.syncBlacklist();
Expand Down
7 changes: 7 additions & 0 deletions src/ts/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ export function addMessageListener<T>(type: string, listener: (args: T) => void)

// #region BackgroundPage

export type SiteID = 'startpage';

export interface BackgroundPage extends Window {
// Blacklist
setBlacklist(blacklist: string): Promise<void>;
Expand All @@ -197,6 +199,11 @@ export interface BackgroundPage extends Window {
updateSubscription(id: SubscriptionId): Promise<void>;
updateAllSubscriptions(): Promise<void>;

// Extra Site
hasSiteEnable(site: SiteID): Promise<boolean>;
requestEnableSite(site: SiteID): Promise<boolean>;
enableSite(site: SiteID): Promise<void>;

// Auth
getAuthToken(interactive: boolean): Promise<string>;
removeCachedAuthToken(token: string): Promise<void>;
Expand Down
73 changes: 59 additions & 14 deletions src/ts/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,60 @@ function $(id: string): HTMLElement | null {
return document.getElementById(id) as HTMLElement | null;
}

const CONTROL_INFO = [
{
site: /^www.google/,
insert: [
(control: HTMLElement): boolean => {
const resultStats = $('resultStats') as HTMLDivElement | null;
if (!resultStats) {
return false;
}
resultStats.appendChild(control);
return true;
},
(control: HTMLElement): boolean => {
const abCtls = $('ab_ctls') as HTMLOListElement | null;
if (!abCtls) {
return false;
}
const li = document.createElement('li');
li.className = 'ab_ctl';
li.id = 'ubImageSearchControl';
li.appendChild(control);
abCtls.appendChild(li);
return true;
},
],
},
{
site: /^www.startpage/,
insert: [
(control: HTMLElement): boolean => {
const searchFilter = document.querySelector('.search-filters-toolbar__container');
if (!searchFilter) {
return false;
}
const div = document.createElement('div');
div.className = 'search-filters-toolbar__advanced';
div.appendChild(control);
searchFilter.appendChild(div);
return true;
},
(control: HTMLElement): boolean => {
const imageFilter = document.querySelector('.images-filters-toolbar__container');
if (!imageFilter) {
return false;
}
const div = document.createElement('div');
div.appendChild(control);
imageFilter.appendChild(div);
return true;
},
],
},
];

class Main {
blacklists: BlacklistAggregation | null = null;
blacklistUpdate: BlacklistUpdate | null = null;
Expand Down Expand Up @@ -210,22 +264,13 @@ class Main {
control.appendChild(showButton);
control.appendChild(hideButton);

const resultStats = $('resultStats') as HTMLDivElement | null;
if (resultStats) {
resultStats.appendChild(control);
} else {
const abCtls = $('ab_ctls') as HTMLOListElement | null;
if (abCtls) {
const li = document.createElement('li');
li.className = 'ab_ctl';
li.id = 'ubImageSearchControl';
li.appendChild(control);
abCtls.appendChild(li);
} else {
return;
for (const info of CONTROL_INFO) {
if (info.site.exec(window.location.hostname)) {
if (!info.insert.some((insert): boolean => insert(control))) {
return;
}
}
}

this.updateControl();
}

Expand Down
22 changes: 21 additions & 1 deletion src/ts/inspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,26 @@ const ENTRY_INFO: EntryInfo[] = [
actionClass: 'ubNewsSearchAction',
display: 'default',
},
{
id: 'StartPage.Search.Default',
target: '.w-gl__result',
targetDepth: 0,
pageLink: '> .w-gl__result-title',
pageLinkType: 'default',
actionParent: '',
actionClass: 'ubDefaultAction',
display: 'default',
},
{
id: 'StartPage.Search.Image',
target: '.ig-gl__list .image-container',
targetDepth: 0,
pageLink: 'span.site',
pageLinkType: 'default',
actionParent: '',
actionClass: 'ubImageSearchAction',
display: 'imageSearch',
},
];

export interface InspectResult {
Expand Down Expand Up @@ -223,7 +243,7 @@ export function inspectEntry(elem: HTMLElement): InspectResult | null {
}
pageUrl = parsed.searchParams.get('q') || pageUrl;
} else {
pageUrl = (pageLink as HTMLAnchorElement).href;
pageUrl = pageLink.getAttribute('href') as string;
}
let actionParent!: HTMLElement;
if (info.actionParent) {
Expand Down
Loading