web_mobile

This commit is contained in:
2026-11-08 17:32:34 +08:00
parent 28bba64611
commit 974a1fb10b
73 changed files with 5506 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,96 @@
import { user } from "@web/core/user";
import mobile from "@web_mobile/js/services/core";
import { isIosApp } from "@web/core/browser/feature_detection";
import { url } from "@web/core/utils/urls";
const DEFAULT_AVATAR_SIZE = 128;
export const accountMethodsForMobile = {
url,
/**
* Update the user's account details on the mobile app
*
* @returns {Promise}
*/
async updateAccount() {
if (!mobile.methods.updateAccount) {
return;
}
const base64Avatar = await accountMethodsForMobile.fetchAvatar();
return mobile.methods.updateAccount({
avatar: base64Avatar.substring(base64Avatar.indexOf(',') + 1),
name: user.name,
username: user.login,
});
},
/**
* Fetch current user's avatar as PNG image
*
* @returns {Promise} resolved with the dataURL, or rejected if the file is
* empty or if an error occurs.
*/
fetchAvatar() {
const avatarUrl = accountMethodsForMobile.url('/web/image', {
model: 'res.users',
field: 'image_medium',
id: user.userId,
});
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
canvas.width = DEFAULT_AVATAR_SIZE;
canvas.height = DEFAULT_AVATAR_SIZE;
const context = canvas.getContext('2d');
const image = new Image();
image.addEventListener('load', () => {
context.drawImage(image, 0, 0, DEFAULT_AVATAR_SIZE, DEFAULT_AVATAR_SIZE);
resolve(canvas.toDataURL('image/png'));
});
image.addEventListener('error', reject);
image.src = avatarUrl;
});
},
};
/**
* Mixin to hook into the controller record's saving method and
* trigger the update of the user's account details on the mobile app.
*
* @mixin
* @name UpdateDeviceAccountControllerMixin
*
*/
const UpdateDeviceAccountControllerMixin = {
/**
* @override
*/
async save() {
const isSaved = await this._super(...arguments);
if (!isSaved) {
return false;
}
const updated = accountMethodsForMobile.updateAccount();
// Crapy workaround for unupdatable Odoo Mobile App iOS (Thanks Apple :@)
if (!isIosApp()){
await updated;
}
return true;
},
};
export async function updateAccountOnMobileDevice() {
const updated = accountMethodsForMobile.updateAccount();
// Crapy workaround for unupdatable Odoo Mobile App iOS (Thanks Apple :@)
if (!isIosApp()){
await updated;
}
}
/**
* Trigger the update of the user's account details on the mobile app.
*/
accountMethodsForMobile.updateAccount();
export default {
UpdateDeviceAccountControllerMixin,
updateAccountOnMobileDevice,
};

View File

@@ -0,0 +1,49 @@
import { browser } from "@web/core/browser/browser";
import mobile from "@web_mobile/js/services/core";
import { download, downloadFile } from "@web/core/network/download";
function extractPathFromUrl(url) {
const parsedUrl = URL.parse(url);
return parsedUrl ? `${parsedUrl.pathname}${parsedUrl.search}` : url;
}
const _download = download._download;
download._download = async function (options) {
if (mobile.methods.downloadFile) {
if (odoo.csrf_token) {
options.csrf_token = odoo.csrf_token;
}
options.url = extractPathFromUrl(options.url);
mobile.methods.downloadFile(options);
// There is no need to wait downloadFile because we delegate this to
// Download Manager Service where error handling will be handled correclty.
// On our side, we do not want to block the UI and consider the request
// as success.
return Promise.resolve();
} else {
return _download.apply(this, arguments);
}
};
const _downloadFile = downloadFile._download;
downloadFile._download = async function (data, filename, mimetype) {
if (!mobile.methods.downloadFile) {
return _downloadFile.apply(this, arguments);
}
const isUrl = !filename && !mimetype && typeof data === "string";
if (isUrl) {
mobile.methods.downloadFile({
form: { method: "GET" },
url: extractPathFromUrl(data)
});
} else {
browser.console.warn(
"downloadFile: the native saveFile bridge only supports URL downloads; ignoring Blob/string content."
);
}
return Promise.resolve();
};

View File

@@ -0,0 +1,12 @@
import { registry } from "@web/core/registry";
import mobile from "@web_mobile/js/services/core";
function mobileErrorHandler(env, error, originalError) {
if (mobile.methods.crashManager) {
error.originalError = originalError;
mobile.methods.crashManager(error);
}
}
registry
.category("error_handlers")
.add("web_mobile.errorHandler", mobileErrorHandler, { sequence: 3 });

View File

@@ -0,0 +1,23 @@
import { EventBus } from "@odoo/owl";
export class HookEventBus extends EventBus {
/**
@param {{}} hooks
@param {Function} [hooks.onAddListener]
@param {Function} [hooks.onRemoveListener]
*/
constructor(hooks = {}) {
super();
this.hooks = hooks;
}
addEventListener(eventName, listener) {
super.addEventListener(eventName, listener);
this.hooks.onAddListener?.(eventName, listener);
}
removeEventListener(eventName, listener) {
super.removeEventListener(eventName, listener);
this.hooks.onRemoveListener?.(eventName, listener);
}
}

View File

@@ -0,0 +1,89 @@
import { HookEventBus } from "@web_mobile/js/hook_event_bus";
import { Plugin, usePlugin } from "@odoo/owl";
import { services } from "@web/core/services";
import { registry } from "@web/core/registry";
import { session } from "@web/session";
import mobile from "@web_mobile/js/services/core";
import { shortcutItem, switchAccountItem } from "./user_menu_items";
const userMenuRegistry = registry.category("user_menuitems");
export class MobilePlugin extends Plugin {
/** @private */
timeBetweenReadsInMs = session.time_between_reads_in_ms || 100;
/** @private */
idInterval = null;
setup() {
let listenerCount = 0;
this.bus = new HookEventBus({
onAddListener: (eventName, listener) => {
listenerCount++;
if (listenerCount === 1) {
this.enableReader();
}
},
onRemoveListener: (eventName, listener) => {
listenerCount--;
if (listenerCount === 0) {
this.stopReader();
}
},
});
if (mobile.methods.addHomeShortcut) {
userMenuRegistry.add("web_mobile.shortcut", shortcutItem);
}
if (mobile.methods.switchAccount) {
// remove "Log Out" and "My Odoo.com Account"
userMenuRegistry.remove("log_out");
userMenuRegistry.remove("odoo_account");
userMenuRegistry.add("web_mobile.switch", switchAccountItem);
}
}
enableReader() {
if (mobile.methods.enableReader && mobile.methods.getReaderData) {
mobile.methods.enableReader().catch((e) => console.error(e));
if (!this.idInterval) {
this.idInterval = setInterval(async () => {
try {
const value = await mobile.methods.getReaderData();
if (value.success) {
const data = value.data;
if (data.length > 0) {
this.bus.trigger("mobile_reader_scanned", { data });
}
}
} catch (e) {
console.error(e);
}
}, this.timeBetweenReadsInMs);
}
}
}
stopReader() {
if (this.idInterval) {
clearInterval(this.idInterval);
this.idInterval = null;
}
}
}
services.add(MobilePlugin);
/**
* -----------------------------------------------------------------------------
* @todo owl3 migration
* temporary - to remove when all use of the mobile service are removed
* -----------------------------------------------------------------------------
*/
registry.category("services").add("mobile", {
start() {
return usePlugin(MobilePlugin);
},
});

View File

@@ -0,0 +1,108 @@
/* global OdooDeviceUtility */
/* global OdooDevicePolyfill */
import { uniqueId } from "@web/core/utils/functions";
import { location, browser } from "@web/core/browser/browser";
import { parseSearchQuery } from "@web/core/browser/router";
import { patch } from "@web/core/utils/patch";
import { BackButtonManager } from "@web/core/utils/hooks";
const available = typeof OdooDeviceUtility !== "undefined";
let DeviceUtility;
const deferreds = {};
export const methods = {};
if (available) {
DeviceUtility = OdooDeviceUtility;
delete window.OdooDeviceUtility;
}
/**
* Responsible for invoking native methods which called from JavaScript
*
* @param {String} name name of action want to perform in mobile
* @param {Object} args extra arguments for mobile
*
* @returns Promise Object
*/
function native_invoke(name, args) {
if (args === undefined) {
args = {};
}
const id = uniqueId();
args = JSON.stringify(args);
DeviceUtility.execute(name, args, id);
return new Promise(function (resolve, reject) {
deferreds[id] = {
successCallback: resolve,
errorCallback: reject,
};
});
}
/**
* Manages deferred callback from initiate from native mobile
*
* @param {String} id callback id
* @param {Object} result
*/
window.odoo.native_notify = function (id, result) {
if (Object.prototype.hasOwnProperty.call(deferreds, id)) {
if (result.success) {
deferreds[id].successCallback(result);
} else {
deferreds[id].errorCallback(result);
}
}
};
const plugins = available ? JSON.parse(DeviceUtility.list_plugins()) : [];
plugins.forEach((plugin) => {
methods[plugin.name] = function (args) {
return native_invoke(plugin.action, args);
};
});
let polyfills = {};
if (window.OdooDevicePolyfill) {
polyfills = OdooDevicePolyfill;
}
/**
* Use to notify an uri hash change on native devices (ios / android)
*/
if (methods.hashChange) {
let currentSearch;
browser.addEventListener("popstate", function () {
const search = parseSearchQuery(location.search);
if (JSON.stringify(currentSearch) !== JSON.stringify(search)) {
methods.hashChange(search);
}
currentSearch = search;
});
}
patch(BackButtonManager.prototype, {
_activate() {
if (methods.overrideBackButton) {
document.addEventListener("backbutton", this._boundPerformLatestBackAction);
methods.overrideBackButton({ enabled: true });
} else {
super._activate();
}
},
_deactivate() {
if (methods.overrideBackButton) {
document.removeEventListener("backbutton", this._boundPerformLatestBackAction);
methods.overrideBackButton({ enabled: false });
} else {
super._deactivate();
}
},
});
export default {
methods,
polyfills,
};

View File

@@ -0,0 +1,40 @@
import { _t } from "@web/core/l10n/translation";
import { useService } from "@web/core/utils/hooks";
import mobile from "@web_mobile/js/services/core";
export function shortcutItem() {
const menu = useService("menu");
const notification = useService("notification");
return {
type: "item",
id: "web_mobile.shortcut",
description: _t("Add to Home Screen"),
callback: () => {
const currentAppMenu = menu.getCurrentApp();
if (currentAppMenu) {
const base64Icon = currentAppMenu.webIconData;
mobile.methods.addHomeShortcut({
title: document.title,
shortcut_url: document.URL,
web_icon: base64Icon.substring(base64Icon.indexOf(",") + 1),
});
} else {
notification.add(_t("No shortcut for Home Menu"));
}
},
sequence: 100,
};
}
export function switchAccountItem() {
return {
type: "item",
id: "web_mobile.switch",
description: _t("Switch/Add Account"),
callback: () => {
mobile.methods.switchAccount();
},
sequence: 100,
};
}

View File

@@ -0,0 +1,14 @@
import { registry } from "@web/core/registry";
import { formView } from "@web/views/form/form_view";
import { updateAccountOnMobileDevice } from "@web_mobile/js/core/mixins";
class ResUsersPreferenceController extends formView.Controller {
onRecordSaved(record) {
return updateAccountOnMobileDevice();
}
}
registry.category("views").add("res_users_preferences_form", {
...formView,
Controller: ResUsersPreferenceController,
});

View File

@@ -0,0 +1,41 @@
import { patch } from "@web/core/utils/patch";
import { shareTargetService } from "@web/webclient/share_target/share_target_service";
import mobile from "@web_mobile/js/services/core";
patch(shareTargetService, {
async _getShareTargetFiles() {
if (!mobile.methods.getShareTargetFiles) {
return super._getShareTargetFiles();
}
/**
* {
* "success" : true,
* "data" : [
* {
* uri: "content://com.google.android.apps.nbu.files.provider/2/1000006851"
* name: "name.jpg"
* type: "image/jpeg",
* },
* ...]
*/
const response = await mobile.methods.getShareTargetFiles();
if (response.success) {
const files = [];
for (let i = 0; i < response.data.length; i++) {
const { name, uri, type } = response.data[i];
// this is a fake rpc call to mobile apps.
// The app will stream the file content to avoid the risk of some Out of Memory
const fakeRpc = await fetch(
`/share_target.localhost/?uri=${encodeURIComponent(uri)}`
);
if (!fakeRpc.ok) {
throw new Error(`Unable to share file: ${name}`);
}
const blob = await fakeRpc.blob();
files.push(new File([blob], name, { type }));
}
return files;
}
return [];
},
});