Commit ff6e8ed0 authored by Wei Lee's avatar Wei Lee Committed by Commit Bot

[CCA WebUI] Promisify existing callbacks in browser_proxy

Bug: 980846
Test: Launch CCA with no error shows

Change-Id: I808d0c2c5a99e8c068227645e03c8a619310da59
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2058932
Commit-Queue: Wei Lee <wtlee@chromium.org>
Reviewed-by: default avatarShik Chen <shik@chromium.org>
Cr-Commit-Position: refs/heads/master@{#743041}
parent d15a4619
...@@ -12,28 +12,43 @@ import {BrowserProxy} from './browser_proxy_interface.js'; ...@@ -12,28 +12,43 @@ import {BrowserProxy} from './browser_proxy_interface.js';
*/ */
class ChromeAppBrowserProxy { class ChromeAppBrowserProxy {
/** @override */ /** @override */
getVolumeList(callback) { async getVolumeList() {
chrome.fileSystem.getVolumeList(callback); try {
// Await here to handle the case if it is rejected.
return await util.promisify(chrome.fileSystem.getVolumeList)();
} catch (e) {
console.error('Failed to get volume list', e);
return null;
}
} }
/** @override */ /** @override */
requestFileSystem(options, callback) { async requestFileSystem(options) {
chrome.fileSystem.requestFileSystem(options, callback); try {
// Await here to handle the case if it is rejected.
return await util.promisify(chrome.fileSystem.requestFileSystem)(options);
} catch (e) {
console.error('Failed to request file system', e);
return null;
}
} }
/** @override */ /** @override */
localStorageGet(keys, callback) { localStorageGet(keys) {
chrome.storage.local.get(keys, callback); return util.promisify(chrome.storage.local.get.bind(chrome.storage.local))(
keys);
} }
/** @override */ /** @override */
localStorageSet(items, callback) { localStorageSet(items) {
chrome.storage.local.set(items, callback); return util.promisify(chrome.storage.local.set.bind(chrome.storage.local))(
items);
} }
/** @override */ /** @override */
localStorageRemove(items, callback) { localStorageRemove(items) {
chrome.storage.local.remove(items, callback); return util.promisify(
chrome.storage.local.remove.bind(chrome.storage.local))(items);
} }
/** @override */ /** @override */
......
...@@ -7,32 +7,39 @@ ...@@ -7,32 +7,39 @@
* @interface * @interface
*/ */
export class BrowserProxy { export class BrowserProxy {
/** @param {function(!Array<!chrome.fileSystem.Volume>=)} callback */ /**
getVolumeList(callback) {} * @return {!Promise<?Array<!chrome.fileSystem.Volume>>}
* @abstract
*/
async getVolumeList() {}
/** /**
* @param {!chrome.fileSystem.RequestFileSystemOptions} options * @param {!chrome.fileSystem.RequestFileSystemOptions} options
* @param {function(!FileSystem=)} callback * @return {!Promise<?FileSystem>}
* @abstract
*/ */
requestFileSystem(options, callback) {} async requestFileSystem(options) {}
/** /**
* @param {(string|!Array<string>|!Object)} keys * @param {(string|!Array<string>|!Object)} keys
* @param {function(!Object)} callback * @return {!Promise<!Object>}
* @abstract
*/ */
localStorageGet(keys, callback) {} async localStorageGet(keys) {}
/** /**
* @param {!Object<string>} items * @param {!Object<string>} items
* @param {function()=} callback * @return {!Promise}
* @abstract
*/ */
localStorageSet(items, callback) {} async localStorageSet(items) {}
/** /**
* @param {(string|!Array<string>)} items * @param {(string|!Array<string>)} items
* @param {function()=} callback * @return {!Promise}
* @abstract
*/ */
localStorageRemove(items, callback) {} async localStorageRemove(items) {}
/** /**
* @return {!Promise<boolean>} * @return {!Promise<boolean>}
......
...@@ -18,17 +18,19 @@ function NOTIMPLEMENTED() { ...@@ -18,17 +18,19 @@ function NOTIMPLEMENTED() {
*/ */
class WebUIBrowserProxy { class WebUIBrowserProxy {
/** @override */ /** @override */
getVolumeList(callback) { async getVolumeList() {
NOTIMPLEMENTED(); NOTIMPLEMENTED();
return null;
} }
/** @override */ /** @override */
requestFileSystem(options, callback) { async requestFileSystem(options) {
NOTIMPLEMENTED(); NOTIMPLEMENTED();
return null;
} }
/** @override */ /** @override */
localStorageGet(keys, callback) { async localStorageGet(keys) {
let sanitizedKeys = []; let sanitizedKeys = [];
if (typeof keys === 'string') { if (typeof keys === 'string') {
sanitizedKeys = [keys]; sanitizedKeys = [keys];
...@@ -49,30 +51,24 @@ class WebUIBrowserProxy { ...@@ -49,30 +51,24 @@ class WebUIBrowserProxy {
result[key] = value === null ? {} : value; result[key] = value === null ? {} : value;
} }
callback(result); return result;
} }
/** @override */ /** @override */
localStorageSet(items, callback) { async localStorageSet(items) {
for (const [key, val] of Object.entries(items)) { for (const [key, val] of Object.entries(items)) {
window.localStorage.setItem(key, JSON.stringify(val)); window.localStorage.setItem(key, JSON.stringify(val));
} }
if (callback) {
callback();
}
} }
/** @override */ /** @override */
localStorageRemove(items, callback) { async localStorageRemove(items) {
if (typeof items === 'string') { if (typeof items === 'string') {
items = [items]; items = [items];
} }
for (const key of items) { for (const key of items) {
window.localStorage.removeItem(key); window.localStorage.removeItem(key);
} }
if (callback) {
callback();
}
} }
/** @override */ /** @override */
......
...@@ -80,7 +80,7 @@ export class ConstraintsPreferrer { ...@@ -80,7 +80,7 @@ export class ConstraintsPreferrer {
restoreResolutionPreference_(key) { restoreResolutionPreference_(key) {
// TODO(inker): Return promise and await it to assure preferences are loaded // TODO(inker): Return promise and await it to assure preferences are loaded
// before any access. // before any access.
browserProxy.localStorageGet({[key]: {}}, (values) => { browserProxy.localStorageGet({[key]: {}}).then((values) => {
this.prefResolution_ = {}; this.prefResolution_ = {};
for (const [deviceId, {width, height}] of Object.entries(values[key])) { for (const [deviceId, {width, height}] of Object.entries(values[key])) {
this.prefResolution_[deviceId] = new Resolution(width, height); this.prefResolution_[deviceId] = new Resolution(width, height);
...@@ -234,9 +234,8 @@ export class VideoConstraintsPreferrer extends ConstraintsPreferrer { ...@@ -234,9 +234,8 @@ export class VideoConstraintsPreferrer extends ConstraintsPreferrer {
* @private * @private
*/ */
restoreFpsPreference_() { restoreFpsPreference_() {
browserProxy.localStorageGet( browserProxy.localStorageGet({deviceVideoFps: {}})
{deviceVideoFps: {}}, .then((values) => this.prefFpses_ = values.deviceVideoFps);
(values) => this.prefFpses_ = values.deviceVideoFps);
} }
/** /**
......
...@@ -128,8 +128,8 @@ export class App { ...@@ -128,8 +128,8 @@ export class App {
* @private * @private
*/ */
setupToggles_() { setupToggles_() {
browserProxy.localStorageGet( browserProxy.localStorageGet({expert: false})
{expert: false}, ({expert}) => state.set(state.State.EXPERT, expert)); .then(({expert}) => state.set(state.State.EXPERT, expert));
document.querySelectorAll('input').forEach((element) => { document.querySelectorAll('input').forEach((element) => {
element.addEventListener( element.addEventListener(
'keypress', 'keypress',
...@@ -160,8 +160,8 @@ export class App { ...@@ -160,8 +160,8 @@ export class App {
}); });
if (element.dataset.key !== undefined) { if (element.dataset.key !== undefined) {
// Restore the previously saved state on startup. // Restore the previously saved state on startup.
browserProxy.localStorageGet( browserProxy.localStorageGet(payload(element))
payload(element), .then(
(values) => util.toggleChecked( (values) => util.toggleChecked(
assertInstanceof(element, HTMLInputElement), assertInstanceof(element, HTMLInputElement),
values[element.dataset.key])); values[element.dataset.key]));
......
...@@ -92,7 +92,7 @@ function initInternalTempDir() { ...@@ -92,7 +92,7 @@ function initInternalTempDir() {
/** /**
* Reads file entries from the directory. * Reads file entries from the directory.
* @param {?DirectoryEntry} dir Directory entry to be read. * @param {?DirectoryEntry} dir Directory entry to be read.
* @return {!Promise<!Array<!FileEntry>>} Promise for the read file entries. * @return {!Promise<!Array<!Entry>>} Promise for the read file entries.
*/ */
function readDir(dir) { function readDir(dir) {
return !dir ? Promise.resolve([]) : new Promise((resolve, reject) => { return !dir ? Promise.resolve([]) : new Promise((resolve, reject) => {
...@@ -116,32 +116,28 @@ function readDir(dir) { ...@@ -116,32 +116,28 @@ function readDir(dir) {
* Initializes the directory in the external file system. * Initializes the directory in the external file system.
* @return {!Promise<?DirectoryEntry>} Promise for the directory result. * @return {!Promise<?DirectoryEntry>} Promise for the directory result.
*/ */
function initExternalDir() { async function initExternalDir() {
return new Promise((resolve) => { const volumes = await browserProxy.getVolumeList();
browserProxy.getVolumeList((volumes) => { if (volumes === null) {
if (volumes) { return null;
for (let i = 0; i < volumes.length; i++) {
const volumeId = volumes[i].volumeId;
if (volumeId.indexOf('downloads:Downloads') !== -1 ||
volumeId.indexOf('downloads:MyFiles') !== -1) {
browserProxy.requestFileSystem(
volumes[i], (fs) => resolve([fs && fs.root, volumeId]));
return;
}
} }
const getFileSystemRoot = async (volume) => {
const fs = await browserProxy.requestFileSystem(volume);
return fs === null ? null : fs.root;
};
for (const volume of volumes) {
if (!volume.volumeId.includes('downloads:MyFiles')) {
continue;
} }
resolve([null, null]); const root = await getFileSystemRoot(volume);
}); const entries = await readDir(root);
}) const downloadsDir = entries.find(
.then(([dir, volumeId]) => {
if (volumeId && volumeId.indexOf('downloads:MyFiles') !== -1) {
return readDir(dir).then((entries) => {
return entries.find(
(entry) => entry.name === 'Downloads' && entry.isDirectory); (entry) => entry.name === 'Downloads' && entry.isDirectory);
}); return downloadsDir ? /** @type {!DirectoryEntry} */ (downloadsDir) : null;
} }
return dir; return null;
});
} }
/** /**
...@@ -258,9 +254,8 @@ export function initialize(promptMigrate) { ...@@ -258,9 +254,8 @@ export function initialize(promptMigrate) {
const checkAcked = new Promise((resolve) => { const checkAcked = new Promise((resolve) => {
// ack 0: User has not yet acknowledged to migrate pictures. // ack 0: User has not yet acknowledged to migrate pictures.
// ack 1: User acknowledges to migrate pictures to Downloads. // ack 1: User acknowledges to migrate pictures to Downloads.
browserProxy.localStorageGet( browserProxy.localStorageGet({ackMigratePictures: 0})
{ackMigratePictures: 0}, .then((values) => resolve(values.ackMigratePictures >= 1));
(values) => resolve(values.ackMigratePictures >= 1));
}); });
const ackMigrate = () => const ackMigrate = () =>
browserProxy.localStorageSet({ackMigratePictures: 1}); browserProxy.localStorageSet({ackMigratePictures: 1});
...@@ -289,7 +284,13 @@ export function initialize(promptMigrate) { ...@@ -289,7 +284,13 @@ export function initialize(promptMigrate) {
// Pictures taken by old Camera App may not have IMG_ or VID_ prefix. // Pictures taken by old Camera App may not have IMG_ or VID_ prefix.
return readDir(internalDir) return readDir(internalDir)
.then((entries) => { .then((entries) => {
return entries.some((entry) => !hasThumbnailPrefix(entry)); return entries.some((entry) => {
if (entry.isDirectory) {
return false;
}
const fileEntry = /** @type {!FileEntry} */ (entry);
return !hasThumbnailPrefix(fileEntry);
});
}) })
.then((migrateNeeded) => { .then((migrateNeeded) => {
if (migrateNeeded) { if (migrateNeeded) {
...@@ -482,7 +483,11 @@ export function getFile(dir, name, create) { ...@@ -482,7 +483,11 @@ export function getFile(dir, name, create) {
export function getEntries() { export function getEntries() {
return readDir(externalDir).then((entries) => { return readDir(externalDir).then((entries) => {
return entries.filter((entry) => { return entries.filter((entry) => {
if (!hasVideoPrefix(entry) && !hasImagePrefix(entry)) { if (entry.isDirectory) {
return false;
}
const fileEntry = /** @type {!FileEntry} */ (entry);
if (!hasVideoPrefix(fileEntry) && !hasImagePrefix(fileEntry)) {
return false; return false;
} }
return entry.name.match(/_(\d{8})_(\d{6})(?: \((\d+)\))?/); return entry.name.match(/_(\d{8})_(\d{6})(?: \((\d+)\))?/);
......
...@@ -102,9 +102,8 @@ export class Options { ...@@ -102,9 +102,8 @@ export class Options {
this.toggleMirror_.addEventListener('click', () => this.saveMirroring_()); this.toggleMirror_.addEventListener('click', () => this.saveMirroring_());
// Restore saved mirroring states per video device. // Restore saved mirroring states per video device.
browserProxy.localStorageGet( browserProxy.localStorageGet({mirroringToggles: {}})
{mirroringToggles: {}}, .then((values) => this.mirroringToggles_ = values.mirroringToggles);
(values) => this.mirroringToggles_ = values.mirroringToggles);
// Remove the deprecated values. // Remove the deprecated values.
browserProxy.localStorageRemove( browserProxy.localStorageRemove(
['effectIndex', 'toggleMulti', 'toggleMirror']); ['effectIndex', 'toggleMulti', 'toggleMirror']);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment