Welcome! Please enter your instance information below.
34 |
35 |
Change Instance
36 |
37 |
Home Instance URL:
38 |
39 |
40 |
Please enter a valid URL (ex. 'https://lemmy.ca")
41 |
42 |
Home Instance Type:
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
Change Display
53 |
54 |
You can modify the list of instances in the popup menu by editing this field. This is helpful if you have
55 | accounts on more than one instance, or even if you like jumping between instances. Remove the instances that you
56 | don't need, and if you make a mistake then you can 'Reset to Default'.
57 |
Please list one instance per line, and use the format "button-text, url"
The community ` + targetCommunity + ` does not exist on this instance (yet). This can happen if you are the first person to try and open it in this instance. Someone will need to prompt this instance to fetch the community from the original instance. This task can be trigerred by entering the community URL (ex. ` + targetInstance + `/c/` + targetCommunity + `) or identifier (ex. !` + targetCommunity + `@` + targetInstance + `) into the search page (reference).
You can do this by clicking on the button below, and then coming back after some time. Don't worry about the "No results" message, the fetch process would have started in the background. Alternatively, you can copy one of the codes above and do the search manually at https://` + CURRENT_HOST + `/search.\n\n You can also just view the community on the foreign instance.
`)
73 |
74 | let btnOpenSearchLemmy = createButton('Trigger a search');
75 | btnOpenSearchLemmy.style.cssText = `
76 | padding: .375rem .75rem;
77 | margin: 0rem 2rem 2rem 2rem;
78 | width: 50%;
79 | border: none;
80 | border-radius: 5px;
81 | font-weight: 400;
82 | text-align: center;
83 | color: white;
84 | `;
85 | btnOpenSearchLemmy.style.backgroundColor = '#175a4c';
86 |
87 | let btnHomeLemmy = createButton('Go to my home instance');
88 | btnHomeLemmy.style.cssText = `
89 | padding: .375rem .75rem;
90 | margin: 1rem 2rem .5rem 2rem;
91 | width: 50%;
92 | border: none;
93 | border-radius: 5px;
94 | font-weight: 400;
95 | text-align: center;
96 | color: white;
97 | `;
98 | btnHomeLemmy.style.backgroundColor = '#5f35ae';
99 |
100 | let btnCommunityLemmy = createButton('Open community on foreign instance');
101 | btnCommunityLemmy.style.cssText = `
102 | padding: .375rem .75rem;
103 | margin: 1rem 2rem .5rem 2rem;
104 | width: 50%;
105 | border: none;
106 | border-radius: 5px;
107 | font-weight: 400;
108 | text-align: center;
109 | color: white;
110 | `;
111 | btnCommunityLemmy.style.backgroundColor = '#363636';
112 |
113 | let txtHomeInstance = selectedInstance ? createMessage(`Your home instance is ${selectedInstance}.`) : createMessage(`You have not set a home instance yet.`);
114 |
115 | const changeInstanceInstructions = [
116 | '1) Click on the extension icon in the browser toolbar',
117 | '2) Press "Change my home instance" and type in your home instance URL',
118 | '3) Press "Toggle home instance type" to switch between "Lemmy" and "Kbin". (default is "Lemmy")',
119 | ];
120 |
121 | const txtChangeInstance = createDropdown('How to change home instance', changeInstanceInstructions);
122 |
123 | // --------- Add Event Listeners -------- //
124 | btnHomeLemmy.addEventListener('click', () => {
125 | if (selectedInstance) {
126 | window.location.href = selectedInstance;
127 | } else { alert('No valid instance has been set.') }
128 | });
129 |
130 | btnOpenSearchLemmy.addEventListener('click', () => {
131 | window.location.href = 'https://' + CURRENT_HOST + '/search?q=' + '!' + targetCommunity + '%40' + targetInstance + '&type=All&listingType=All&page=1&sort=TopAll';
132 | });
133 |
134 | btnCommunityLemmy.addEventListener('click', () => {
135 | window.location.href = 'https://' + targetInstance + '/c/' + targetCommunity;
136 | });
137 |
138 | // ---------- Append elements ----------- //
139 | if (!document.querySelector('#instance-assistant-sidebar') && (await getSetting('runOnCommunityNotFound'))) { // prevent duplicate elements
140 | const hideHelp = await getSetting('hideHelp');
141 | if (!hideHelp) {container.appendChild(txtErrorPage);}
142 | container.appendChild(btnOpenSearchLemmy)
143 | container.appendChild(btnCommunityLemmy);
144 | container.appendChild(btnHomeLemmy);
145 | container.appendChild(txtHomeInstance);
146 | if (!hideHelp) {container.appendChild(txtChangeInstance);}
147 | TARGET_ELEMENT.insertBefore(container, TARGET_ELEMENT.firstChild);
148 | }
149 |
150 | if (mayBeFrontend(targetInstance)) {
151 |
152 | console.log('may be frontend')
153 |
154 | let txtAlternateRedirect = createMessage('
IMPORTANT: Based on your URL ' + targetInstance + ', you may be using a custom frontend. You can try getting the community from the main domain:
47 |
48 | **Safari:** No immediate plans. While I can port the extension to Safari, I can't sign and publish it without a recent MacOS device.
49 |
50 | **Other browsers:** No immediate plans. For most other browsers, you should be able to download from either the Chrome or Firefox stores.
51 |
52 | If you have thoughts or want to contribute, you can join the discussion here: https://lemmy.ca/c/instance_assistant
53 |
54 |
55 |
56 |
57 |
58 |
59 | # Features
60 |
61 |
62 |
63 | **Support** for Lemmy and Kbin instances + custom frontends such as Alexandrite and Photon
64 |
65 |
66 |
67 | **Post to Lemmy/Kbin:**
68 | * Instance Assistant can generate a draft post with autofilled title/link/body
69 | * For most news sites, videos, and other webpages, you can use the popup menu
70 | * For images, you can right-click on the image itself
71 |
72 |
73 |
74 | **Search for posts:**
75 | * Find and open all posts that have a link to the site you are on. Use it to find posts about news articles, videos, and more
76 |
77 |
78 |
79 | **Search for communities and content without leaving the page:**
80 | * You can use the popup menu or sidebar to search for communities (powered by [lemmyverse.net](https://lemmyverse.net/communities)), and for content (powered by [search-lemmy.com](https://search-lemmy.com))
81 |
82 |
83 |
84 | **Redirect to your home instance:**
85 | * When you are on a foreign instance, buttons will be available in the sidebar to open the **community**, **post**, or **user (NEW)** in your home instance, allowing you to participate immediately
86 |
87 |
88 |
89 | **Open links in home instance:**
90 | * If you come across a Lemmy/Kbin link anywhere on the web, you can right click to open it in your home instance
91 |
92 |
93 |
94 | **Upgraded Pages:**
95 | * 'Community not found' pages now have better information and buttons to trigger a fetch, open the community in the source instance, and more. This also supports alternative front-ends. [See it in action here](https://lemmy.ca/c/fakecommunity@example.com)
96 | * `/communities` pages will have the non-functional 'subscribe' buttons replaced, to make it easier when browsing other instances.
97 |
98 |
99 |
100 | **Customizable:**
101 | * Customizable list of instances in popup/sidebar to let you quickly switch home instances. This is great for if you have multiple accounts on different instances
102 | * You can change the behaviour of the extension and customize the actual Lemmy/Kbin site interface, making your browsing experience your own.
103 |
104 |
105 |
106 |
107 | ### I'm new to Lemmy/Kbin, what is this?
108 |
109 | Lemmy and Kbin are a part of the Fediverse, a network of interconnected social media platforms that work similar to Reddit. This extension is designed to make it easier to use these platforms and make the most of decentralized social media while mimizing the difficulties that may come with it.
110 |
111 | Say, for example, you may make an account on `lemmy.ca`. You may google a community or topic and come across a page on a different instance (ex. `lemmy.ml/c/technology`). If you want to subscribe to the community, you will need to copy the code (`!technology@lemmy.ml`), open your home instance, and then paste it into the search page. If you want to comment on a post, you would then try to track it down by scrolling through the community.
112 |
113 | This extension will let you jump to the version on your home instance, allowing you to subscribe and participate immediately.
114 |
115 | There are many other features as well, and hopefully many more to come! :)
116 |
117 |
118 |
119 | # Contributing
120 |
121 | You can contribute to this project in a number of ways:
122 |
123 | 🐛 **Report bugs & suggest features:** If you find a bug or want a new feature, you can discuss in the [Support Community](https://lemmy.ca/c/instance_assistant) or open an issue on GitHub.
124 |
125 | 💻 **Contribute code:** You can find guidance [on the wiki](https://github.com/cynber/lemmy-instance-assistant/wiki/Development-Process)
126 |
127 | 🌐 **Translate:** If you want to help translate the extension, you will soon be able to do so. I will update this section once it is ready.
128 |
129 | 💛 **Donate:** If you want to support the project financially, you can do so by clicking the sponsor button on this page, or through [ko-fi.com/cynber](https://ko-fi.com/cynber)
130 |
131 |
132 |
133 |
134 |
135 | # Other Links
136 |
137 | * [Recent Updates](https://github.com/cynber/lemmy-instance-assistant/wiki#recent-updates)
138 | * [Open Issues](https://github.com/cynber/lemmy-instance-assistant/issues)
139 | * [What is being worked on?](https://github.com/users/cynber/projects/1)
140 | * [Credits](https://github.com/cynber/lemmy-instance-assistant/wiki#credits)
141 |
142 |
143 |
144 | # Screenshots
145 |
146 | This is not a complete list of features, but it should give you an idea of what the extension can do. I will update these screenshots every now and then, so the UI may have changed since these were taken.
147 |
148 |
149 |
150 |
Popup Menu with redirect, community search, and more
151 |
Improved 'community not found' page, with button to triger a fetch and more
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
Redirect button in sidebar of foreign Lemmy instance
162 |
Redirect button in sidebar of foreign Kbin instance
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
Redirect button for Photon Frontend
173 |
Redirect button for Alexandrite Frontend
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
Improved '/communities' page on foreign instances
184 |
Persistent sidebar version of popup menu
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
Right click context menu to open any links in your home instance
195 |
Change display settings, such as hiding the default sidebar
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
--------------------------------------------------------------------------------
/src/m3-background.js:
--------------------------------------------------------------------------------
1 | // --------------------------------------
2 | // COPIED FROM utils.js
3 | function getStorageAPI() {
4 | let storageAPI;
5 | if (typeof browser !== 'undefined' && browser.storage && browser.storage.local) {
6 | storageAPI = browser.storage.local;
7 | } else if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
8 | storageAPI = chrome.storage.local;
9 | } else {
10 | throw new Error('Storage API is not supported in this browser.');
11 | }
12 |
13 | return storageAPI;
14 | }
15 | function getBrowserAPI() {
16 | let browserAPI;
17 | if (typeof browser !== 'undefined' && browser.storage && browser.storage.local) {
18 | browserAPI = browser;
19 | } else if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
20 | browserAPI = chrome;
21 | } else {
22 | throw new Error('Browser API is not supported in this browser.');
23 | }
24 | return browserAPI;
25 | }
26 | async function getAllSettings() {
27 | const storageAPI = getStorageAPI();
28 | const allSettings = await storageAPI.get('settings');
29 | if (!allSettings || !allSettings.settings) {
30 | await setAllSettings(defaultSettings);
31 | return defaultSettings;
32 | }
33 | return await storageAPI.get('settings');
34 | }
35 | async function getSetting(settingName) {
36 | const allSettings = await getAllSettings();
37 | return allSettings.settings[settingName];
38 | }
39 | async function hasSelectedInstance() {
40 | const selectedInstance = await getSetting('selectedInstance');
41 | return selectedInstance !== undefined && selectedInstance !== "";
42 | }
43 | async function hasSelectedType() {
44 | const selectedType = await getSetting('selectedType');
45 | return selectedType !== undefined && selectedType !== "";
46 | }
47 | async function loadStorage(key) {
48 | const { value } = await browser.storage.local.get(key);
49 | return value;
50 | }
51 | async function p2l_getPostData() {
52 | const storageAPI = getBrowserAPI();
53 | return new Promise((resolve, reject) => {
54 | storageAPI.tabs.query({ active: true, currentWindow: true }, function (tabs) {
55 | const activeTab = tabs[0];
56 | const postData = {
57 | title: activeTab.title,
58 | url: activeTab.url
59 | };
60 | resolve(postData);
61 | });
62 | });
63 | }
64 | // --------------------------------------
65 |
66 | // --------------------------------------
67 | // Handle redirects within a Lemmy site
68 | // - Sometimes when navigating within a Lemmy site, the content scripts won't run despite the URL matching the pattern. This is a workaround for that.
69 | // --------------------------------------
70 | chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
71 | if (tab.url?.startsWith("chrome://") || tab.url?.startsWith("chrome-extension://")) {
72 | return undefined;
73 | }
74 | if (changeInfo.status === "complete") {
75 | if (
76 | /^https?:\/\/.*\/c\//.test(tab.url) ||
77 | /^https?:\/\/.*\/communities\//.test(tab.url) ||
78 | /^https?:\/\/.*\/post\//.test(tab.url)
79 | ) {
80 | chrome.scripting.executeScript({
81 | target: { tabId: tabId },
82 | files: ["utils.js", "content-sidebar.js", "content-general.js"]
83 | });
84 | }
85 | }
86 | });
87 |
88 |
89 | // --------------------------------------
90 | // Handle context menu clicks
91 | // --------------------------------------
92 | chrome.contextMenus.onClicked.addListener(async (info, tab) => {
93 | if (info.menuItemId === "redirect" && info.linkUrl) {
94 |
95 | let sourceHost = new URL(info.linkUrl).hostname;
96 | let sourcePath = new URL(info.linkUrl).pathname;
97 |
98 | if (sourcePath.includes("/c/") || sourcePath.includes("/m/")) {
99 | const communityName = sourcePath.match(/\/[cm]\/([^/@]+)/)[1];
100 | const sourceInstance = sourcePath.includes("@") ?
101 | sourcePath.match(/\/[cm]\/[^/@]+@([^/]+)/)[1] : sourceHost;
102 | const selectedType = await getSetting("selectedType");
103 | const selectedInstance = await getSetting("selectedInstance");
104 |
105 | if (!selectedInstance) {
106 | chrome.tabs.update(tab.id, { url: 'https://github.com/cynber/lemmy-instance-assistant#setup' });
107 | return false;
108 | }
109 |
110 | const communityPrefix = selectedType ? (selectedType === "lemmy" ? "/c/" : "/m/") : "/c/";
111 | const redirectURL = selectedInstance + communityPrefix + communityName + '@' + sourceInstance;
112 |
113 | chrome.tabs.update(tab.id, { url: redirectURL });
114 |
115 | } else {
116 | chrome.tabs.update(tab.id, { url: 'https://github.com/cynber/lemmy-instance-assistant/wiki/Sorry-that-didn\'t-work...' });
117 | // TODO: Add a popup to explain this
118 | }
119 | } else if (info.menuItemId === "post-image" && info.srcUrl) {
120 |
121 | if (await hasSelectedInstance() && await hasSelectedType()) {
122 |
123 | const type = await getSetting("selectedType");
124 | const instance = await getSetting("selectedInstance");
125 | const postData = await p2l_getPostData();
126 |
127 | if (type === "lemmy") {
128 | const url = instance + "/create_post";
129 | console.log(url, postData, info, tab, type, instance)
130 | const createdTab = await chrome.tabs.create({ url: url });
131 |
132 |
133 | // Listen for tab updates to check for loading completion
134 | chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
135 | console.log(changeInfo.status)
136 | if (tabId === createdTab.id) {
137 | chrome.tabs.onUpdated.removeListener(listener); // Remove the listener
138 | console.log(postData.title);
139 | console.log(postData.url);
140 |
141 | // Fill in form after the tab is fully loaded
142 | chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
143 | if (tabId === createdTab.id && changeInfo.status === "complete") {
144 | chrome.tabs.onUpdated.removeListener(listener); // Remove the listener
145 |
146 | // Fill in form after the tab is fully loaded
147 | chrome.scripting.executeScript({
148 | target: { tabId: createdTab.id },
149 | function: fillFormScript,
150 | args: [{
151 | postDataTitle: postData.title,
152 | infoSrcUrl: info.srcUrl,
153 | postDataUrl: postData.url
154 | }]
155 | });
156 | }
157 | });
158 |
159 | function fillFormScript(args) {
160 | const EVENT_OPTIONS = { bubbles: true, cancelable: false, composed: true };
161 | const EVENTS = {
162 | BLUR: new Event("blur", EVENT_OPTIONS),
163 | CHANGE: new Event("change", EVENT_OPTIONS),
164 | INPUT: new Event("input", EVENT_OPTIONS),
165 | };
166 |
167 | const postTitleInput = document.querySelector("#post-title");
168 | const postURLInput = document.querySelector("#post-url");
169 | const postBodyInput = document.querySelector("textarea[id^='markdown-textarea-']");
170 |
171 | postTitleInput.select();
172 | postTitleInput.value = args.postDataTitle;
173 | postTitleInput.dispatchEvent(EVENTS.INPUT);
174 |
175 | postURLInput.select();
176 | postURLInput.value = args.infoSrcUrl;
177 | postURLInput.dispatchEvent(EVENTS.INPUT);
178 |
179 | postBodyInput.select();
180 | postBodyInput.value = "Source: " + args.postDataUrl;
181 | postBodyInput.dispatchEvent(EVENTS.INPUT);
182 | }
183 | }
184 | });
185 |
186 | } else if (type === "kbin") {
187 | const url = instance + "/new?url=" + info.srcUrl + "&title=" + postData.title + "&body=Source: " + postData.url;
188 | await chrome.tabs.create({ url: url });
189 | }
190 |
191 | } else { alert("No valid instance has been set. Please select an instance in the popup using 'Change my home instance'."); }
192 | }
193 | });
194 |
195 | chrome.runtime.onInstalled.addListener(() => {
196 | chrome.contextMenus.create({
197 | id: "redirect",
198 | title: "Redirect to home instance",
199 | contexts: ["link"],
200 | targetUrlPatterns: ["http://*/c/*", "https://*/c/*", "http://*/p/*", "https://*/p/*", "http://*/m/*", "https://*/m/*"],
201 | });
202 | chrome.contextMenus.create({
203 | id: "post-image",
204 | title: "Post this image",
205 | contexts: ["image"],
206 | targetUrlPatterns: ["http://*/*", "https://*/*"]
207 | }, () => void chrome.runtime.lastError,
208 | );
209 | });
210 |
211 |
212 |
213 | // --------------------------------------
214 | // Set default values on install/update
215 | // --------------------------------------
216 |
217 | chrome.runtime.onInstalled.addListener(async ({ reason }) => {
218 |
219 | // Set default values on install/update
220 | // TODO: fix the utils import so we can just use initializeSettingsWithDefaults()
221 | if (reason === 'install' || reason === 'update') {
222 |
223 | async function backgroundInitializeSettings() {
224 |
225 | const defaultSettings = {
226 | hideSidebarLemmy: false,
227 | hideSidebarKbin: false,
228 | instanceList: [
229 | { name: "lemmy.world", url: "https://lemmy.world" },
230 | { name: "lemmy.ca", url: "https://lemmy.ca" },
231 | { name: "lemm.ee", url: "https://lemm.ee" },
232 | { name: "kbin.social", url: "https://kbin.social" },
233 | ],
234 | runOnCommunitySidebar: true,
235 | runOnCommunityNotFound: true,
236 | hideHelp: false,
237 | selectedInstance: '', // users are forced to set this
238 | selectedType: 'lemmy', // lemmy or kbin
239 | theme: 'dark', // **NOT IMPLEMENTED YET**
240 | toolSearchCommunity_openInLemmyverse: false,
241 | };
242 |
243 | let storageAPI = chrome.storage.local;
244 | let allSettings = await storageAPI.get('settings');
245 |
246 | if (!allSettings || !allSettings.settings) {
247 | await storageAPI.set({ 'settings': defaultSettings });
248 | } else {
249 | for (const settingName of Object.keys(defaultSettings)) {
250 | if (!allSettings.settings.hasOwnProperty(settingName)) {
251 | allSettings.settings[settingName] = defaultSettings[settingName];
252 | }
253 | }
254 | await storageAPI.set({ 'settings': allSettings.settings });
255 | }
256 | }
257 | await backgroundInitializeSettings();
258 | }
259 |
260 | // Open settings page when extension is first installed
261 | if (reason === 'install') {
262 | chrome.tabs.create({ url: 'page-settings/settings.html' });
263 | }
264 | });
265 |
--------------------------------------------------------------------------------
/src/content-sidebar.js:
--------------------------------------------------------------------------------
1 | // =========================================================================== //
2 | // Injects buttons and links into the sidebar of Lemmy communities and posts. //
3 | // =========================================================================== //
4 |
5 | setTimeout(() => {
6 | const pageURL = window.location.href;
7 |
8 | if (isLemmyCommunity(pageURL) ||
9 | isLemmyPost(pageURL) ||
10 | isLemmyUser(pageURL) ||
11 | isKbinCommunity(pageURL) ||
12 | isLemmyPhoton() ||
13 | isLemmyAlexandrite()) {
14 |
15 | async function loadSelectedInstance() {
16 |
17 | const selectedInstance = await getSetting('selectedInstance');
18 | const hideHelp = await getSetting('hideHelp');
19 |
20 | // ====================================== //
21 | // --------- Set up injectables --------- //
22 | // ====================================== //
23 |
24 | let createButton = (text) => {
25 | const button = document.createElement('button');
26 | button.setAttribute('type', 'button');
27 | button.textContent = text;
28 | button.setAttribute('id', 'instance-assistant-sidebar');
29 | return button;
30 | };
31 |
32 | const createMessage = (text) => {
33 | const paragraph = document.createElement('p');
34 | paragraph.style.cssText = `font-size: 0.8rem; color: #939496;`;
35 | paragraph.innerHTML = text;
36 | paragraph.setAttribute('id', 'instance-assistant-sidebar');
37 | return paragraph;
38 | };
39 |
40 | const createDropdown = (text, options) => {
41 | const container = document.createElement('div');
42 | const dropdownText = document.createElement('p');
43 | const dropdownList = document.createElement('ul');
44 | dropdownText.innerHTML = "▼ " + text + " ▼";
45 | dropdownText.style.cssText = `cursor: pointer; font-size: 0.8rem; color: #939496;; text-decoration: underline;`;
46 | dropdownList.style.cssText = `list-style: none; padding: 0; margin: 0; font-size: 0.8rem; color: #939496;`;
47 |
48 | dropdownList.style.display = 'none';
49 | dropdownText.addEventListener('click', () => {
50 | dropdownList.style.display = dropdownList.style.display === 'none' ? 'block' : 'none';
51 | dropdownText.innerHTML = dropdownList.style.display === 'none' ? "▼ " + text + " ▼" : "▲ " + text + " ▲";
52 | });
53 |
54 | options.forEach((option) => {
55 | const listItem = document.createElement('li');
56 | listItem.innerHTML = option;
57 | listItem.style.cssText = `padding: 0.5rem 0rem;`;
58 | dropdownList.appendChild(listItem);
59 | });
60 |
61 | container.appendChild(dropdownText);
62 | container.appendChild(dropdownList);
63 | return container;
64 | };
65 |
66 | let btnRedirectKbin = createButton('Open in my home instance');
67 | btnRedirectKbin.style.cssText = `
68 | padding: 0.75rem;
69 | margin: 1rem 0rem .5rem 0rem;
70 | width: 100%;
71 | height: 100%;
72 | display: block;
73 | border: var(--kbin-button-secondary-border);
74 | text-align: center;
75 | color: white;
76 | font-size: 0.85rem;
77 | font-weight: 400;
78 | cursor: pointer;
79 | `;
80 | btnRedirectKbin.style.backgroundColor = '#5f35ae';
81 |
82 | let btnRedirectLemmy = createButton('Open in my home instance');
83 | btnRedirectLemmy.style.cssText = `
84 | padding: .375rem .75rem;
85 | margin: 1rem 0rem .5rem 0rem;
86 | width: 100%;
87 | border: none;
88 | border-radius: 5px;
89 | font-weight: 400;
90 | text-align: center;
91 | color: white;
92 | `;
93 | btnRedirectLemmy.style.backgroundColor = '#5f35ae';
94 |
95 | let btnRedirectLemmyAlexandrite = createButton('Open in my home instance');
96 | btnRedirectLemmyAlexandrite.style.cssText = `
97 | padding: .375rem .75rem;
98 | margin: 1rem 0rem .5rem 0rem;
99 | width: 60%;
100 | border: none;
101 | border-radius: 5px;
102 | font-weight: 400;
103 | text-align: center;
104 | color: white;
105 | `;
106 | btnRedirectLemmyAlexandrite.style.backgroundColor = '#5f35ae';
107 |
108 | let containerRedirectLemmyAlexandrite = document.createElement('div');
109 | containerRedirectLemmyAlexandrite.setAttribute('id', 'instance-assistant-sidebar');
110 | containerRedirectLemmyAlexandrite.style.cssText = `
111 | background-color: #19101e;
112 | padding: 0.5rem;
113 | border-radius: 5px;
114 | margin: 0.5rem 0rem 0.5rem 0rem;
115 | text-align: center;
116 | `;
117 |
118 | let btnRedirectLemmyPhoton = createButton('Open in my home instance');
119 | btnRedirectLemmyPhoton.style.cssText = `
120 | padding: .375rem .75rem;
121 | margin: .5rem 0rem .5rem 0rem;
122 | width: 100%;
123 | border: none;
124 | border-radius: 5px;
125 | font-weight: 400;
126 | text-align: center;
127 | color: white;
128 | `;
129 | btnRedirectLemmyPhoton.style.backgroundColor = '#5f35ae';
130 |
131 | let containerRedirectLemmyPhoton = document.createElement('div');
132 | containerRedirectLemmyPhoton.setAttribute('id', 'instance-assistant-sidebar');
133 | containerRedirectLemmyPhoton.style.cssText = `
134 | background-color: #18181b;
135 | padding: 10px;
136 | border-radius: 5px;
137 | border-color: #232326;
138 | border-width: 1px;
139 | margin: 0.5rem -1rem 0.5rem 0rem;
140 | `;
141 |
142 | let btnToPostLemmy = createButton('Find in my home instance');
143 | btnToPostLemmy.style.cssText = `
144 | padding: .375rem .75rem;
145 | margin: 1rem 0rem .5rem 0rem;
146 | width: 100%;
147 | border: none;
148 | border-radius: 5px;
149 | font-weight: 400;
150 | text-align: center;
151 | color: white;
152 | `;
153 | btnToPostLemmy.style.backgroundColor = '#27175a';
154 |
155 | let btnToUserLemmy = createButton('Find user in my home instance');
156 | btnToUserLemmy.style.cssText = `
157 | padding: .375rem .75rem;
158 | margin: 1rem 0rem .5rem 0rem;
159 | width: 100%;
160 | border: none;
161 | border-radius: 5px;
162 | font-weight: 400;
163 | text-align: center;
164 | color: white;
165 | `;
166 | btnToUserLemmy.style.backgroundColor = '#432684';
167 |
168 | // let btnToPostKbin = createButton('Find in my home instance');
169 | // btnToPostKbin.style.cssText = `
170 | // padding: 0.75rem;
171 | // margin: 1rem 0rem .5rem 0rem;
172 | // width: 100%;
173 | // height: 100%;
174 | // display: block;
175 | // border: var(--kbin-button-secondary-border);
176 | // text-align: center;
177 | // color: white;
178 | // font-size: 0.85rem;
179 | // font-weight: 400;
180 | // cursor: pointer;
181 | // `;
182 | // btnToPostKbin.style.backgroundColor = '#27175a';
183 |
184 |
185 | let txtHomeInstance = selectedInstance ? createMessage(`Home Instance: ${selectedInstance}`) : createMessage(`You have not set a home instance yet.`);
186 |
187 | const changeInstanceInstructions = [
188 | '1) Click on the extension icon in the browser toolbar',
189 | '2) Press "Change my home instance" and type in your home instance URL',
190 | '3) Press "Toggle home instance type" to switch between "Lemmy" and "Kbin". (default is "Lemmy")',
191 | ];
192 |
193 | const txtChangeInstance = createDropdown('How to change home instance', changeInstanceInstructions);
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 | const canRedirect = await hasSelectedInstance();
206 | let TARGET_ELEMENT;
207 | let redirectURL = '';
208 |
209 | // ---------- Set Target Element -------- //
210 | switch (true) {
211 | case isKbinCommunity(pageURL) && !isKbinPost(pageURL):
212 | TARGET_ELEMENT = document.querySelector('.section.intro') || document.querySelector('#sidebar .magazine .row');
213 | break;
214 |
215 | case isKbinPost(pageURL):
216 | TARGET_ELEMENT = document.querySelector('.section.intro') || document.querySelector('#sidebar .magazine .row');
217 | break;
218 |
219 | case isLemmyUser(pageURL):
220 | TARGET_ELEMENT = document.querySelector('.person-listing');
221 | break;
222 |
223 | case (isLemmyCommunity(pageURL) && !isLemmyPost(pageURL) && !isLemmyUser(pageURL)):
224 | TARGET_ELEMENT = document.querySelector('.card-body');
225 | break;
226 |
227 | case isLemmyPost(pageURL):
228 | TARGET_ELEMENT = document.querySelector('#sidebarMain').children[0];
229 | break;
230 |
231 | case isLemmyPhoton() && !isLemmyPhotonPost(pageURL):
232 | TARGET_ELEMENT = document.querySelector('.hidden.xl\\:block aside').children[2];
233 | break;
234 |
235 | case isLemmyPhotonPost(pageURL):
236 | TARGET_ELEMENT = document.querySelector('main.p-3');
237 | break;
238 |
239 | case isLemmyAlexandrite():
240 | TARGET_ELEMENT = document.querySelector('.sidebar').children[1];
241 | break;
242 | }
243 |
244 |
245 |
246 |
247 | // ---------- Add Event Listeners -------- //
248 |
249 | // For community redirects
250 | if (!(isLemmyPost(pageURL) ||
251 | isLemmyPhotonPost(pageURL) ||
252 | isLemmyAlexandritePost(pageURL) ||
253 | isLemmyUser(pageURL))) {
254 | redirectURL = await getCommunityRedirectURL(pageURL);
255 | }
256 | function redirectToInstance() {
257 | canRedirect
258 | ? window.location.href = redirectURL
259 | : alert('No valid instance has been set.');
260 | }
261 |
262 | btnRedirectLemmy.addEventListener('click', redirectToInstance);
263 | btnRedirectKbin.addEventListener('click', redirectToInstance);
264 | btnRedirectLemmyAlexandrite.addEventListener('click', redirectToInstance);
265 | btnRedirectLemmyPhoton.addEventListener('click', redirectToInstance);
266 |
267 | // For post redirects
268 | btnToPostLemmy.addEventListener('click', async () => {
269 | if (canRedirect) {
270 |
271 | // prepare variables for fetching
272 | let og_instance = getRealHostname(pageURL)
273 | let postId = (window.location.pathname).split('/post/')[1];
274 |
275 | // if on a photon instance, further split the url
276 | if (isLemmyPhotonPost(pageURL)) {
277 | postId = window.location.pathname.split('/post/')[1].split('/')[1];
278 | }
279 |
280 | // fetch the filtered post list from home instance
281 | const og_Post = await fetchPostFromID("https://"+og_instance, postId);
282 | const matchingPosts = await fetchPostsFromTitle(selectedInstance, og_Post.post.name);
283 | const filteredPosts = await filterPostsByPost(og_Post, matchingPosts);
284 |
285 | // if only one post is found, redirect to it
286 | // else ask if user wants to open all matching posts
287 | if (filteredPosts.length > 0) {
288 | console.log(filteredPosts[0]);
289 | const newPostId = filteredPosts[0].post.id;
290 | const community = filteredPosts[0].community.name;
291 | openPostFromID(selectedInstance, newPostId, community);
292 | //window.location.href = selectedInstance + '/post/' + newPostId;
293 | } else if (filteredPosts.length > 1) {
294 | const approve = confirm(filteredPosts.length + ' matching posts were found. Do you want to open them all?');
295 | if (approve) {
296 | filteredPosts.forEach(post => {
297 | console.log(post);
298 | const community = post.community.name;
299 | openPostFromID(selectedInstance, post.post.id, community);
300 | //window.open(selectedInstance + '/post/' + post.post.id);
301 |
302 | });
303 | }
304 | } else { alert("Post not found in home instance"); }
305 | } else { alert('No valid instance has been set.') }
306 | });
307 |
308 | // btnToPostKbin.addEventListener('click', async () => {
309 | // if (canRedirect) {
310 | // console
311 | // let community;
312 | // let instance;
313 | // let postID;
314 | // const pathParts = window.location.pathname.split('/');
315 | // if (pageURL.includes('@')) {
316 | // community = pathParts[2];
317 | // instance = pathParts[3].split('@')[1];
318 | // postID = pathParts[5];
319 | // } else {
320 | // community = pathParts[2];
321 | // instance = window.location.hostname;
322 | // postID = pathParts[4];
323 | // }
324 | // openPostFromID(selectedInstance, postID, community);
325 | // }
326 | // });
327 |
328 | // For user redirects
329 |
330 | if(isLemmyUser(pageURL)) {
331 | redirectURL = await getUserRedirectURL(pageURL);
332 | }
333 | function redirectToUser() {
334 | canRedirect
335 | ? window.location.href = redirectURL
336 | : alert('No valid instance has been set.');
337 | }
338 |
339 | btnToUserLemmy.addEventListener('click', redirectToUser);
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 | // ---------- Append elements ----------- //
349 | if (!document.querySelector('#instance-assistant-sidebar') && (await getSetting('runOnCommunitySidebar')) && !(await isHomeInstance(pageURL))) { // Prevent duplicate elements
350 | // append community redirect button to community page
351 | if (isLemmyCommunity(pageURL)) {
352 | TARGET_ELEMENT.appendChild(btnRedirectLemmy);
353 | TARGET_ELEMENT.appendChild(txtHomeInstance);
354 | if (!hideHelp) {TARGET_ELEMENT.appendChild(txtChangeInstance);}
355 | }
356 | if (isLemmyPost(pageURL)) {
357 | TARGET_ELEMENT.appendChild(btnToPostLemmy);
358 | TARGET_ELEMENT.appendChild(txtHomeInstance);
359 | if (!hideHelp) {TARGET_ELEMENT.appendChild(txtChangeInstance);}
360 | }
361 | if (isKbinCommunity(pageURL)) {
362 | TARGET_ELEMENT.appendChild(btnRedirectKbin);
363 | TARGET_ELEMENT.appendChild(txtHomeInstance);
364 | if (!hideHelp) {TARGET_ELEMENT.appendChild(txtChangeInstance);}
365 | }
366 | // if (isKbinPost(pageURL)) {
367 | // TARGET_ELEMENT.appendChild(btnToPostKbin);
368 | // TARGET_ELEMENT.appendChild(txtHomeInstance);
369 | // if (!hideHelp) {TARGET_ELEMENT.appendChild(txtChangeInstance);}
370 | // }
371 | if (isLemmyPhoton() && !isLemmyPhotonPost(pageURL)) {
372 | if (!document.querySelector('#instance-assistant-sidebar')) {
373 | containerRedirectLemmyPhoton.appendChild(btnRedirectLemmyPhoton);
374 | containerRedirectLemmyPhoton.appendChild(txtHomeInstance);
375 | if (!hideHelp) {TARGET_ELEMENT.appendChild(txtChangeInstance);}
376 | TARGET_ELEMENT.appendChild(containerRedirectLemmyPhoton);
377 | }
378 | }
379 | // append post redirect button to post page
380 | if (isLemmyPhotonPost(pageURL)) {
381 | TARGET_ELEMENT.insertBefore(btnToPostLemmy, TARGET_ELEMENT.firstChild);
382 | }
383 | if (isLemmyAlexandrite() && !isLemmyAlexandritePost(pageURL)) {
384 | if (!document.querySelector('#instance-assistant-sidebar')) {
385 | containerRedirectLemmyAlexandrite.appendChild(btnRedirectLemmyAlexandrite);
386 | containerRedirectLemmyAlexandrite.appendChild(txtHomeInstance);
387 | if (!hideHelp) {TARGET_ELEMENT.appendChild(txtChangeInstance);}
388 | TARGET_ELEMENT.appendChild(containerRedirectLemmyAlexandrite);
389 | }
390 | }
391 | if (isLemmyAlexandritePost(pageURL)) {
392 | TARGET_ELEMENT.appendChild(btnToPostLemmy);
393 | TARGET_ELEMENT.appendChild(txtHomeInstance);
394 | if (!hideHelp) {TARGET_ELEMENT.appendChild(txtChangeInstance);}
395 | }
396 | // append user redirect button to user page
397 | if (isLemmyUser(pageURL)) {
398 | const userContainer = document.createElement('div');
399 | userContainer.style.cssText = `
400 | display: flex;
401 | flex-direction: column;
402 | align-items: center;
403 | justify-content: center;
404 | `;
405 | userContainer.appendChild(btnToUserLemmy);
406 | userContainer.appendChild(txtHomeInstance);
407 | if (!hideHelp) {userContainer.appendChild(txtChangeInstance);}
408 | TARGET_ELEMENT.parentElement.appendChild(userContainer);
409 | }
410 | }
411 | }
412 | loadSelectedInstance();
413 | }
414 | }, "800");
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | function testFunction() {
2 | console.log("This is a test function.");
3 | }
4 |
5 | let validInstanceURLPattern = /^(http|https):\/\/(?:[\w-]+\.)?[\w.-]+\.[a-zA-Z]{2,}$/;
6 |
7 | // Utility function to get the appropriate storage API based on the browser
8 | function getStorageAPI() {
9 | let storageAPI;
10 | if (typeof browser !== 'undefined' && browser.storage && browser.storage.local) {
11 | storageAPI = browser.storage.local;
12 | } else if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
13 | storageAPI = chrome.storage.local;
14 | } else {
15 | throw new Error('Storage API is not supported in this browser.');
16 | }
17 |
18 | return storageAPI;
19 | }
20 |
21 | function getBrowserAPI() {
22 | let browserAPI;
23 | if (typeof browser !== 'undefined' && browser.storage && browser.storage.local) {
24 | browserAPI = browser;
25 | } else if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
26 | browserAPI = chrome;
27 | } else {
28 | throw new Error('Browser API is not supported in this browser.');
29 | }
30 | return browserAPI;
31 | }
32 |
33 | function doOpenSettings() {
34 | const browserAPI = getBrowserAPI();
35 | browserAPI.tabs.create({ url: '../page-settings/settings.html' });
36 | }
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | // ----------------------------------------------
47 | // SETTINGS FUNCTIONS
48 | // ----------------------------------------------
49 |
50 | // Get all settings
51 | // - returns { settings: { ... } }
52 | async function getAllSettings() {
53 | const storageAPI = getStorageAPI();
54 | const allSettings = await storageAPI.get('settings');
55 | if (!allSettings || !allSettings.settings) {
56 | await setAllSettings(defaultSettings);
57 | return defaultSettings;
58 | }
59 | return await storageAPI.get('settings');
60 | }
61 |
62 | // Get a single setting
63 | // - returns
64 | async function getSetting(settingName) {
65 | const allSettings = await getAllSettings();
66 | return allSettings.settings[settingName];
67 | }
68 |
69 | // Set all settings
70 | // - accepts
71 | async function setAllSettings(settingsObj) {
72 | const storageAPI = getStorageAPI();
73 | await storageAPI.set({ 'settings': settingsObj });
74 | }
75 |
76 | // Set a single setting
77 | // - accepts
78 | async function setSetting(settingName, settingValue) {
79 | const allSettings = await getAllSettings();
80 | allSettings.settings[settingName] = settingValue;
81 | await setAllSettings(allSettings.settings);
82 | }
83 |
84 | // Update multiple settings
85 | // - Usage:
86 | // const settingsToUpdate = {
87 | // theme: 'dark',
88 | // runOnCommunitySidebar: false,
89 | // toolSearchCommunity_openInLemmyverse: false,
90 | // };
91 | // await updateSettings(settingsToUpdate);
92 | async function updateSettings(settingsToUpdate) {
93 | const allSettings = await getAllSettings();
94 | const updatedSettings = { ...allSettings.settings, ...settingsToUpdate };
95 | await setAllSettings(updatedSettings);
96 | }
97 |
98 | const defaultSettings = {
99 | hideSidebarLemmy: false,
100 | hideSidebarKbin: false,
101 | instanceList: [
102 | { name: "lemmy.world", url: "https://lemmy.world" },
103 | { name: "lemmy.ca", url: "https://lemmy.ca" },
104 | { name: "lemm.ee", url: "https://lemm.ee" },
105 | { name: "kbin.social", url: "https://kbin.social" },
106 | ],
107 | runOnCommunitySidebar: true,
108 | runOnCommunityNotFound: true,
109 | hideHelp: false,
110 | selectedInstance: '', // users are forced to set this
111 | selectedType: 'lemmy', // lemmy or kbin
112 | theme: 'dark', // **NOT IMPLEMENTED YET**
113 | toolSearchCommunity_openInLemmyverse: false,
114 | };
115 |
116 | // Reset all settings to the default values
117 | async function resetAllSettingsToDefault() {
118 | await setAllSettings(defaultSettings);
119 | }
120 |
121 | // Reset a single setting to the default value
122 | // - Usage:
123 | // await resetSettingToDefault('theme');
124 | async function resetSettingToDefault(settingName) {
125 | const allSettings = await getAllSettings();
126 | if (defaultSettings.hasOwnProperty(settingName)) {
127 | allSettings.settings[settingName] = defaultSettings[settingName];
128 | await setAllSettings(allSettings.settings);
129 | } else {
130 | throw new Error(`Setting "${settingName}" does not exist in the default settings.`);
131 | }
132 | }
133 |
134 | // Initialize settings with default values
135 | // - This is called when the extension is first installed or updated
136 | // - It checks for missing settings and adds them
137 | async function initializeSettingsWithDefaults() {
138 | const allSettings = await getAllSettings();
139 | if (!allSettings.hasOwnProperty('settings')) {
140 | await setAllSettings(defaultSettings);
141 | } else {
142 | // Check for missing settings and update them
143 | for (const settingName of Object.keys(defaultSettings)) {
144 | if (!allSettings.settings.hasOwnProperty(settingName)) {
145 | allSettings.settings[settingName] = defaultSettings[settingName];
146 | }
147 | }
148 | await setAllSettings(allSettings.settings);
149 | }
150 | }
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 | // ----------------------------------------------
162 | // Determine type of page
163 | // ----------------------------------------------
164 |
165 | function isLoggedInLemmy() {
166 | const loginLink = document.querySelector('a[href="/login"]');
167 | const signupLink = document.querySelector('a[href="/signup"]');
168 | return !(loginLink && signupLink);
169 | }
170 |
171 | function isLoggedInKbin() {
172 | const loginLink = document.querySelectorAll('a.login[href="/login"]');
173 | return !loginLink;
174 | }
175 |
176 | function isLemmySite() {
177 | const metaTag = document.querySelector('meta[name="Description"]');
178 | if (metaTag) {
179 | return metaTag.content === "Lemmy";
180 | } else {
181 | return false;
182 | }
183 | }
184 |
185 | function isLemmyCommunityList(sourceURL) {
186 | const CURRENT_PATH = new URL(sourceURL).pathname;
187 | return (isLemmySite() && CURRENT_PATH === "/communities")
188 | }
189 |
190 | function isLemmyCommunity(sourceURL) {
191 | const CURRENT_PATH = new URL(sourceURL).pathname;
192 | return (isLemmySite() && CURRENT_PATH.includes("/c/"))
193 | }
194 |
195 | function isLemmyCommunityWEAK(sourceURL) {
196 | // For when you can't check the meta tag, like when only the URL is available
197 | const CURRENT_PATH = new URL(sourceURL).pathname;
198 | return (CURRENT_PATH.includes("/c/"))
199 | }
200 |
201 | function isLemmyPost(sourceURL) {
202 | const CURRENT_PATH = new URL(sourceURL).pathname;
203 | return (isLemmySite() && (CURRENT_PATH.includes("/post/")))
204 | }
205 |
206 | function isLemmyUser(sourceURL) {
207 | const CURRENT_PATH = new URL(sourceURL).pathname;
208 | return (isLemmySite() && (CURRENT_PATH.includes("/u/")))
209 | }
210 |
211 | function isLemmyLoadOtherInstance(sourceURL) {
212 | const CURRENT_PATH = new URL(sourceURL).pathname;
213 | return (isLemmyCommunity(sourceURL) && CURRENT_PATH.includes("@"))
214 | }
215 |
216 | function isLemmyCommunityNotFound(sourceURL) {
217 | const hasErrorContainer = document.querySelector('.error-page');
218 | return (isLemmyLoadOtherInstance(sourceURL) && hasErrorContainer)
219 | }
220 |
221 | function isKbinSite() {
222 | // TODO: Add a check for the meta tag
223 | return true;
224 | }
225 |
226 | function isKbinCommunity(sourceURL) {
227 | const CURRENT_PATH = new URL(sourceURL).pathname;
228 | return (isKbinSite() && CURRENT_PATH.includes("/m/"))
229 | }
230 |
231 | function isKbinCommunityWEAK(sourceURL) {
232 | // For when you can't check the meta tag, like when only the URL is available
233 | const CURRENT_PATH = new URL(sourceURL).pathname;
234 | return (CURRENT_PATH.includes("/m/"))
235 | }
236 |
237 | function isKbinPost(sourceURL) {
238 | const CURRENT_PATH = new URL(sourceURL).pathname;
239 | return (isKbinSite() && (CURRENT_PATH.includes("/t/")))
240 | }
241 |
242 | // -------------- Other Frontends ---------------
243 |
244 | function isLemmyPhoton() {
245 | // look for meta tag name="description", and see if it contains "Photon"
246 | const metaTag = document.querySelector('meta[name="description"]');
247 | if (metaTag) {
248 | return metaTag.content.includes("Photon: An alternative lemmy client with a sleek design.");
249 | } else {
250 | return false;
251 | }
252 | }
253 |
254 | function isLemmyAlexandrite() {
255 | return !!document.querySelector('div.sx-stack.f-row.gap-1.align-items-center.mx-4.sx-badge-gray.sx-font-size-2 a[href="https://github.com/sheodox/alexandrite"]');
256 | }
257 |
258 | function isLemmyPhotonPost(sourceURL) {
259 | const CURRENT_PATH = new URL(sourceURL).pathname;
260 | return (isLemmyPhoton() && CURRENT_PATH.includes("/post/"))
261 | }
262 |
263 | function isLemmyAlexandritePost(sourceURL) {
264 | const CURRENT_PATH = new URL(sourceURL).pathname;
265 | return (isLemmyAlexandrite() && CURRENT_PATH.includes("/post/"))
266 | }
267 |
268 | function mayBeFrontend(testURL) {
269 | let testURLHost = testURL;
270 |
271 | // Check if the input is a valid URL
272 | try {
273 | const urlObj = new URL(testURL);
274 | testURLHost = urlObj.hostname;
275 | } catch (error) {
276 | // Input is not a valid URL, use it as is
277 | }
278 |
279 | const hostParts = testURLHost.split('.');
280 | return hostParts.length > 2; // tests for number of parts in the hostname
281 | }
282 |
283 | function getRealHostname(testURL) {
284 | let testURLHost = testURL;
285 |
286 | // Check if the input is a valid URL
287 | try {
288 | const urlObj = new URL(testURL);
289 | testURLHost = urlObj.hostname;
290 | } catch (error) {
291 | // Input is not a valid URL, use it as is
292 | }
293 | // check if testURLHost contains > 1 dot
294 |
295 | if (testURLHost.split('.').length > 2) {
296 | const hostParts = testURLHost.split('.');
297 | return hostParts.slice(1).join('.');
298 | } else {
299 | return testURLHost;
300 | }
301 | }
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 | // ----------------------------------------------
313 | // SELECTED INSTANCE FUNCTIONS
314 | // ----------------------------------------------
315 |
316 | async function hasSelectedInstance() {
317 | const selectedInstance = await getSetting('selectedInstance');
318 | return selectedInstance !== undefined && selectedInstance !== "";
319 | }
320 |
321 | async function hasSelectedType() {
322 | const selectedType = await getSetting('selectedType');
323 | return selectedType !== undefined && selectedType !== "";
324 | }
325 |
326 | async function isHomeInstance(testURL) {
327 | if (!(await hasSelectedInstance())) {
328 | console.log("No selected instance");
329 | return false;
330 | } else {
331 | console.log("Has selected instance");
332 | const selectedInstance = await getSetting('selectedInstance');
333 | const testURLHost = new URL(testURL).hostname;
334 | const selectedInstanceHost = new URL(selectedInstance).hostname;
335 | return testURLHost.endsWith(selectedInstanceHost);
336 | }
337 | }
338 |
339 | async function getCommunityRedirectURL(oldURL) {
340 | const selectedInstance = await getSetting('selectedInstance');
341 | const selectedType = await getSetting('selectedType');
342 |
343 | const communityPrefix = selectedType ? (selectedType === "lemmy" ? "/c/" : "/m/") : "/c/";
344 |
345 | const oldHost = new URL(oldURL).hostname;
346 | const oldPath = new URL(oldURL).pathname;
347 |
348 | const communityName = oldPath.match(/\/[cm]\/([^/@]+)/)[1];
349 | const oldInstance = oldPath.includes("@") ?
350 | oldPath.match(/\/[cm]\/[^/@]+@([^/]+)/)[1] : oldHost;
351 |
352 | const newURL = selectedInstance + communityPrefix + communityName + '@' + oldInstance;
353 |
354 | return newURL;
355 | }
356 |
357 | async function getUserRedirectURL(oldURL) {
358 | const selectedInstance = await getSetting('selectedInstance');
359 | const selectedType = await getSetting('selectedType');
360 |
361 | const oldHost = new URL(oldURL).hostname;
362 | const oldPath = new URL(oldURL).pathname;
363 |
364 | console.log("oldURL:", oldURL, "oldHost:", oldHost, "oldPath:", oldPath);
365 |
366 | const userName = oldPath.match(/\/u\/([^/@]+)/)[1];
367 | const userInstance = oldPath.includes("@") ?
368 | oldPath.match(/\/u\/[^/@]+@([^/]+)/)[1] : oldHost;
369 |
370 | const newURL = selectedInstance + "/u/" + userName + '@' + userInstance;
371 |
372 | console.log("newURL:", newURL);
373 |
374 | return newURL;
375 | }
376 |
377 |
378 | async function getPostRedirectURL(oldURL) {
379 | return oldURL;
380 | }
381 |
382 | async function toggleInstanceType() {
383 | const currentType = await getSetting("selectedType");
384 | const newType = currentType === "lemmy" ? "kbin" : "lemmy";
385 | await setSetting("selectedType", newType);
386 | }
387 |
388 | // INPUT: instance URL (string), post ID (string)
389 | // OUTPUT: post object (JSON)
390 | async function fetchPostFromID(instance, postID) {
391 | console.log("fetch request:", instance + '/api/v3/post?id=' + postID)
392 | const options = { method: 'GET', headers: { accept: 'application/json' } };
393 | try {
394 | const response = await fetch(instance + '/api/v3/post?id=' + postID, options);
395 | const apiResponse = await response.json();
396 | return apiResponse.post_view;
397 | } catch (err) {
398 | console.error(err);
399 | }
400 | }
401 |
402 | // INPUT: instance URL (string), post title (string)
403 | // OUTPUT: post search results (JSON)
404 | async function fetchPostsFromTitle(instance, postTitle) {
405 | console.log("fetch request:", instance + '/api/v3/search?q=' + encodeURIComponent(postTitle) + '&type_=Posts');
406 | const options = { method: 'GET', headers: { accept: 'application/json' } };
407 | try {
408 | console.log("fetch request:", instance + '/api/v3/search?q=' + encodeURIComponent(postTitle) + '&type_=Posts');
409 | const response = await fetch(instance + '/api/v3/search?q=' + encodeURIComponent(postTitle) + '&type_=Posts', options);
410 | const apiResponse = await response.json();
411 | return apiResponse.posts;
412 | } catch (err) {
413 | console.error(err);
414 | }
415 | }
416 |
417 | // INPUT: post object (JSON), post search results (JSON)
418 | // OUTPUT: filtered post search results (JSON)
419 | async function filterPostsByPost(testPost, inputPosts) {
420 | const og_communityName = testPost.community.name;
421 | const og_creatorName = testPost.creator.name;
422 | const og_title = testPost.post.name;
423 | const og_url = testPost.post.url;
424 |
425 | let filteredPosts = inputPosts.filter(post =>
426 | post.community.name === og_communityName &&
427 | post.creator.name === og_creatorName &&
428 | post.post.name === og_title
429 | );
430 |
431 | return filteredPosts;
432 | }
433 |
434 | async function openPostFromID(instance, postID, community) {
435 | const type = await getSetting("selectedType");
436 |
437 | (type === "lemmy") ?
438 | window.location.href = instance + '/post/' + postID :
439 | window.location.href = instance + '/m/' + community + '/t/' + postID;
440 | }
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 | // ----------------------------------------------
454 | // ------------- External Tool ----------------
455 | // ----------------------------------------------
456 |
457 | // External Tool: Search Community through Lemmyverse
458 | async function toolSearchCommunitiesLemmyverse(searchTerm) {
459 | const browserAPI = getBrowserAPI();
460 | if (searchTerm !== "") {
461 | if (await getSetting('toolSearchCommunity_openInLemmyverse')) {
462 | const baseUrl = "https://lemmyverse.net/communities";
463 | const encodedSearchTerm = encodeURIComponent(searchTerm);
464 | browserAPI.tabs.create({ url: `${baseUrl}?query=${encodedSearchTerm}` });
465 | } else {
466 | browserAPI.tabs.create({ url: `../page-search/search.html?query=${encodeURIComponent(searchTerm)}` });
467 | }
468 | } else {
469 | console.log("CommunitySearch: Search term is empty");
470 | }
471 | }
472 |
473 | // External Tool: Search Content through Lemmysearch
474 | function toolSearchContentLemmysearch(searchTerm) {
475 | const browserAPI = getBrowserAPI();
476 | if (searchTerm !== "") {
477 | const baseUrl = "https://www.search-lemmy.com/results";
478 | const encodedSearchTerm = encodeURIComponent(searchTerm);
479 | const finalUrl = `${baseUrl}?query=${encodedSearchTerm}`;
480 | browserAPI.tabs.create({ url: finalUrl });
481 | }
482 | }
483 |
484 |
485 |
486 |
487 |
488 |
489 |
490 |
491 |
492 |
493 | // ----------------------------------------------
494 | // ------------- Posting Tools ----------------
495 | // ----------------------------------------------
496 |
497 | // Helper functions to post a webpage to a community
498 |
499 | // Get the post data from the current tab
500 | // - returns { title: "title", url: "url" }
501 | async function p2l_getPostData() {
502 | const browserAPI = getBrowserAPI();
503 | const tabs = await browserAPI.tabs.query({ active: true, currentWindow: true });
504 | const activeTab = tabs[0];
505 | const postData = {
506 | title: activeTab.title,
507 | url: activeTab.url
508 | };
509 | return postData;
510 | }
511 |
512 | // when on a webpage, open the matching posts in a new tab
513 | async function doOpenMatchingPostsLemmy(testURL) {
514 | const browserAPI = getBrowserAPI();
515 | const selectedType = await getSetting('selectedType');
516 |
517 | if (await hasSelectedInstance() && await hasSelectedType()) {
518 | if (selectedType === "lemmy") {
519 | const selectedInstance = await getSetting('selectedInstance');
520 |
521 | const searchURL = selectedInstance + "/api/v3/search?q=" + testURL;
522 | const [lemmyPostResponse_URL, lemmyPostResponse_BODY] = await Promise.all([
523 | fetch(searchURL + "&type_=Url"),
524 | fetch(searchURL + "&type_=All")
525 | ]);
526 | lemmyPostData = {
527 | posts: [
528 | ...(await lemmyPostResponse_URL.json()).posts,
529 | ...(await lemmyPostResponse_BODY.json()).posts
530 | ]
531 | };
532 | if (lemmyPostData.posts.length <= 0) {
533 | alert("No posts found for this URL.");
534 | } else if (lemmyPostData.posts.length === 1) {
535 | lemmyPostData.posts.forEach(post => {
536 | const post_id = post.counts.post_id;
537 | console.log("Post ID:", post_id);
538 | browserAPI.tabs.create({ url: selectedInstance + "/post/" + post_id });
539 | });
540 | } else if (lemmyPostData.posts.length > 1) {
541 | // tell user how many posts there are and ask if it's ok to open them
542 | const confirmOpen = confirm("There are " + lemmyPostData.posts.length + " posts for this URL. Open them all?");
543 | if (confirmOpen) {
544 | lemmyPostData.posts.forEach(post => {
545 | const post_id = post.counts.post_id;
546 | console.log("Post ID:", post_id);
547 | browserAPI.tabs.create({ url: selectedInstance + "/post/" + post_id });
548 | });
549 | }
550 | }
551 | } else if (selectedType === "kbin") {
552 | alert("This feature is not yet available for Kbin instances.");
553 | }
554 | } else { alert("No valid instance has been set. Please select an instance in the popup using 'Change my home instance'."); }
555 | }
556 |
557 | async function doOpenMatchingPostsKbin(testURL) {
558 | // TODO: Implement this
559 | alert("This feature is not yet available for Kbin instances.");
560 | }
561 |
562 | // When on a webpage, post it to a community
563 | async function doCreatePost() {
564 | const browserAPI = getBrowserAPI();
565 | if (await hasSelectedInstance() && await hasSelectedType()) {
566 | const postData = await p2l_getPostData();
567 |
568 | const instance = await getSetting("selectedInstance");
569 | const type = await getSetting("selectedType");
570 |
571 | if (type === "lemmy") {
572 | const url = instance + "/create_post";
573 | const createdTab = await browserAPI.tabs.create({ url: url });
574 | const listener = (tabId, changeInfo) => {
575 | if (tabId === createdTab.id && (changeInfo.status === "complete" || changeInfo.status === "loading")) {
576 |
577 |
578 | browserAPI.tabs.onUpdated.removeListener(listener);
579 |
580 | // Fill in form after the tab is fully loaded
581 | browserAPI.scripting.executeScript({
582 | target: { tabId: createdTab.id },
583 | func: async (postData) => {
584 | const EVENT_OPTIONS = {bubbles: true, cancelable: false, composed: true};
585 | const EVENTS = {
586 | BLUR: new Event("blur", EVENT_OPTIONS),
587 | CHANGE: new Event("change", EVENT_OPTIONS),
588 | INPUT: new Event("input", EVENT_OPTIONS),
589 | };
590 |
591 | const postTitleInput = document.querySelector("#post-title");
592 | const postURLInput = document.querySelector("#post-url");
593 |
594 | postTitleInput.select();
595 | postTitleInput.value = postData.title;
596 | postTitleInput.dispatchEvent(EVENTS.INPUT);
597 |
598 | postURLInput.select();
599 | postURLInput.value = postData.url;
600 | postURLInput.dispatchEvent(EVENTS.INPUT);
601 | },
602 | args: [postData]
603 | }).catch(error => {
604 | console.error("Script execution error:", error);
605 | });
606 |
607 | window.close();
608 | }
609 | };
610 |
611 | browserAPI.tabs.onUpdated.addListener(listener);
612 |
613 | } else if (type === "kbin") {
614 | const url = instance + "/new?url=" + postData.url + "&title=" + postData.title;
615 | await browserAPI.tabs.create({ url: url });
616 | }
617 | } else { alert("No valid instance has been set. Please select an instance in the popup using 'Change my home instance'."); }
618 | }
619 |
620 |
621 |
622 |
623 |
624 |
625 |
626 |
627 |
628 |
629 | // ----------------------------------------------
630 | // ---------- General DOM Manipulation ----------
631 | // ----------------------------------------------
632 |
633 | //Used for offset removal
634 | function removeClassByWildcard(divClass) {
635 | // If the class ends with a "*", then it matches all classes that start with the given class name.
636 | if (divClass.endsWith("*")) {
637 | divClass = divClass.replace("*", "");
638 | // Get all elements with the given class name.
639 | const elements = document.getElementsByTagName("div");
640 | const re = new RegExp("(^|s)" + divClass + "(s|$)");
641 | const result = [];
642 | let className = "";
643 |
644 | for (let i = 0; i < elements.length; i++) {
645 | if (re.test(elements[i].className)) {
646 | console.log("Match: " + elements[i]);
647 | result.push(elements[i]);
648 | for (let y = 0; y < elements[i].classList.length; y++) {
649 | if (elements[i].classList[y].indexOf(divClass) !== -1) {
650 | className = elements[i].classList[y];
651 | console.log(className);
652 | }
653 | }
654 | }
655 | }
656 | // Remove the class from all elements.
657 | for (let i = 0; i < result.length; i++) {
658 | result[i].classList.remove(className);
659 | }
660 | } else {
661 | // Otherwise, the class must match exactly.
662 | const elements = document.querySelectorAll("[class=" + divClass + "]");
663 |
664 | // Remove the class from all elements.
665 | for (let i = 0; i < elements.length; i++) {
666 | elements[i].classList.remove(divClass);
667 | }
668 | }
669 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------