Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: check configured bookmark connection #63

Merged
merged 1 commit into from
Apr 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified docs/screenshot-options.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 4 additions & 4 deletions src/entrypoints/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ export default defineBackground({
main() {
registerSyncBookmarks(new GitHubBookmarksLoader());

const syncBookmarks = getSyncBookmarks();
const bookmarkSyncService = getSyncBookmarks();

const jobs = defineJobScheduler();

console.log('💈 Background script loaded for', chrome.runtime.getManifest().name);

browser.runtime.onInstalled.addListener(details => {
console.log('Extension installed:', details);
syncBookmarks();
bookmarkSyncService.synchronizeBookmarks();
});

jobs.scheduleJob({
Expand All @@ -28,7 +28,7 @@ export default defineBackground({
duration: 1000 * 3600, // Runs hourly
execute() {
console.log('Scheduled sync bookmarks job');
syncBookmarks();
bookmarkSyncService.synchronizeBookmarks();
},
});

Expand All @@ -38,7 +38,7 @@ export default defineBackground({
date: Date.now() + (1000 * 30), // 30 seconds after extension init (browser start)
execute() {
console.log('Syncing bookmarks on browser startup');
syncBookmarks();
bookmarkSyncService.synchronizeBookmarks();
},
});
},
Expand Down
4 changes: 3 additions & 1 deletion src/entrypoints/options/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
</label>
</p>
</form>
<button id="check-connection-btn">Check Connection</button>
<p id="connection-message"></p>
<script src="./options.js" type="module"></script>
</body>

</html>
</html>
39 changes: 39 additions & 0 deletions src/entrypoints/options/options.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
html {
min-width: 550px;
min-height: 14rem;
overflow-x: hidden;
/* Required to hide horizontal scroll on Firefox */
}
Expand Down Expand Up @@ -50,3 +51,41 @@ label.text-input>.divider {
hr {
margin-bottom: 15px;
}

#check-connection-btn {
width: 11rem;
cursor: pointer;
display: inline-block;
}

#check-connection-btn:disabled {
cursor: not-allowed;
}

#check-connection-btn.in-progress {
cursor: progress;
}

#connection-message {
border-radius: 4px;
padding: 10px 15px;
margin: 10px 0;
display: block;
box-sizing: border-box;
}

#connection-message.hidden {
display: none;
}

#connection-message.success {
color: #003300;
background-color: #ccffcc;
border: 1px solid #004400;
}

#connection-message.error {
color: #330000;
background-color: #ffcccc;
border: 1px solid #440000;
}
91 changes: 91 additions & 0 deletions src/entrypoints/options/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,100 @@
import 'webext-base-css';
import './options.css';
import optionsStorage from '@/utils/options-storage.js';
import {getSyncBookmarks} from '@/utils/bookmarksync.js';

const bookmarkSyncService = getSyncBookmarks();

/**
* @typedef {'success' | 'error' | 'in-progress' | null} CheckStatus
*/

async function init() {
await optionsStorage.syncForm('#options-form');

const form = document.querySelector('#options-form');
const checkConnectionButton = document.querySelector('#check-connection-btn');
const connectionMessage = document.querySelector('#connection-message');

let isChecking = false;
let cancelCurrentCheck = false;

/**
* Displays a connection message.
* @param {CheckStatus} status - The status of the connection check.
* @param {string} message - The message to display.
*/
const showConnectionMessage = (status, message) => {
connectionMessage.textContent = message;
connectionMessage.className = status || '';
connectionMessage.classList.remove('hidden');
};

/**
* Clear the connection message display.
*/
const clearConnectionMessage = () => {
connectionMessage.textContent = '';
connectionMessage.className = '';
connectionMessage.classList.add('hidden');
};

/**
* Updates the text and appearance of the check connection button given a status.
* @param {CheckStatus} status - The status of the connection check.
*/
const updateButton = status => {
checkConnectionButton.className = status || '';
checkConnectionButton.textContent = status === 'in-progress' ? 'Checking…' : 'Check Connection';
checkConnectionButton.disabled = status === 'in-progress' || !form.checkValidity();
};

const resetCheckConnection = () => {
if (!isChecking) {
updateButton(null);
clearConnectionMessage();
}
};

checkConnectionButton.addEventListener('click', async () => {
if (!form.checkValidity() || isChecking) {
return;
}

isChecking = true;
cancelCurrentCheck = false;
clearConnectionMessage();
updateButton('in-progress');

try {
await bookmarkSyncService.validateBookmarks();
if (cancelCurrentCheck) {
updateButton(null);
return;
}

updateButton('success');
showConnectionMessage('success', 'Success');
} catch (error) {
if (cancelCurrentCheck) {
updateButton(null);
return;
}

updateButton('error');
showConnectionMessage('error', error.message);
} finally {
isChecking = false;
cancelCurrentCheck = false;
}
});

form.addEventListener('options-sync:form-synced', () => {
cancelCurrentCheck = true;
resetCheckConnection();
});

resetCheckConnection();
}

init();
4 changes: 2 additions & 2 deletions src/entrypoints/popup/popup.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import './popup.css';
import logo from '@/assets/bookmarksync-icon.svg';
import {getSyncBookmarks} from '@/utils/bookmarksync.js';

const syncBookmarks = getSyncBookmarks();
const bookmarkSyncService = getSyncBookmarks();

document.querySelector('#bookmarksync-logo').src = logo;

Expand All @@ -13,7 +13,7 @@ syncButton.addEventListener('click', async () => {
syncButton.textContent = 'Synchronizing...';
syncButton.disabled = true;
try {
await syncBookmarks(true);
await bookmarkSyncService.synchronizeBookmarks(true);
} catch (error) {
console.error('Error triggering manual bookmark sync:', error);
} finally {
Expand Down
44 changes: 34 additions & 10 deletions src/utils/bookmarksync.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import {browser} from 'wxt/browser';
import {defineProxyService} from '@webext-core/proxy-service';
import {registerSchema, validate} from '@hyperjump/json-schema/draft-07';
import {AuthenticationError, BookmarksDataNotValidError, DataNotFoundError} from './errors.js';
import {
BookmarkSourceNotConfiguredError, AuthenticationError, BookmarksDataNotValidError, DataNotFoundError, RepositoryNotFoundError,
} from './errors.js';
import bookmarkSchema from '@/utils/bookmarks.1-0-0.schema.json';

registerSchema(bookmarkSchema);

export const [registerSyncBookmarks, getSyncBookmarks] = defineProxyService(
'SyncBookmarksService',
loader => async function (force = false) {
class BookmarkSyncService {
#loader;

constructor(loader) {
this.#loader = loader;
}

async synchronizeBookmarks(force = false) {
try {
console.log(`Starting ${force ? 'forced ' : ''}bookmark synchronization`);

const bookmarkFiles = await loader.load(force);
const bookmarkFiles = await this.#loader.load({force});

if (bookmarkFiles) {
await validateBookmarkFiles(bookmarkFiles);
Expand All @@ -23,21 +30,39 @@ export const [registerSyncBookmarks, getSyncBookmarks] = defineProxyService(
console.log('Bookmarks synchronized');
}
} catch (error) {
if (error instanceof AuthenticationError) {
if (error instanceof BookmarkSourceNotConfiguredError) {
// Do not error out - perhaps the user just didn't yet set it up
console.log('Could not sync because the required configuration values are not set');
} else if (error instanceof AuthenticationError) {
console.error('Authentication error:', error.message, error.originalError);
await notify('Authentication failed', 'Please check your Personal Access Token settings.');
await notify('Authentication failed', error.message);
} else if (error instanceof DataNotFoundError) {
console.error('Data not found error:', error.message, error.originalError);
await notify('Data not found', 'The bookmarks could not be found. Please check the configured repo and path.');
await notify('Data not found', error.message);
} else if (error instanceof BookmarksDataNotValidError) {
console.error('Bookmark data not valid error:', error.message);
await notify('Invalid bookmark data', `Canceling synchronization: ${error.message}`);
} else if (error instanceof RepositoryNotFoundError) {
console.error('Repository not found error:', error.message);
await notify('Repo not found', error.message);
} else {
console.error('Error during synchronization:', error);
await notify('Synchronization failed', 'Failed to update bookmarks.');
}
}
},
}

async validateBookmarks() {
console.log('Validating the configured source of bookmarks');

const bookmarkFiles = await this.#loader.load({force: true, cacheEtag: false});
await validateBookmarkFiles(bookmarkFiles);
}
}

export const [registerSyncBookmarks, getSyncBookmarks] = defineProxyService(
'SyncBookmarksService',
loader => new BookmarkSyncService(loader),
);

async function validateBookmarkFiles(bookmarkFiles) {
Expand All @@ -47,7 +72,6 @@ async function validateBookmarkFiles(bookmarkFiles) {
for (const bookmarkFile of bookmarkFiles) {
const validationResult = validator(bookmarkFile);
if (!validationResult.valid) {
console.log(validationResult);
const name = bookmarkFile.name || '<name not defined>';
throw new BookmarksDataNotValidError(`The bookmarks file with name '${name}' is not valid`);
}
Expand Down
19 changes: 18 additions & 1 deletion src/utils/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ class AuthenticationError extends Error {
}
}

class BookmarkSourceNotConfiguredError extends Error {
constructor(message) {
super(message);
this.name = 'BookmarkSourceNotConfiguredError';
}
}

class DataNotFoundError extends Error {
constructor(message, originalError) {
super(message);
Expand All @@ -21,4 +28,14 @@ class BookmarksDataNotValidError extends Error {
}
}

export {AuthenticationError, DataNotFoundError, BookmarksDataNotValidError};
class RepositoryNotFoundError extends Error {
constructor(message, originalError) {
super(message);
this.name = 'RepositoryNotFoundError';
this.originalError = originalError;
}
}

export {
AuthenticationError, DataNotFoundError, BookmarksDataNotValidError, BookmarkSourceNotConfiguredError, RepositoryNotFoundError,
};
Loading
Loading