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

Do not use DOMContentLoaded for registering the viewer handler #378

Merged
merged 8 commits into from
Dec 9, 2022
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
15 changes: 2 additions & 13 deletions appinfo/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,16 @@
$eventDispatcher->addListener(
'OCA\Files::loadAdditionalScripts',
function () {
\OCP\Util::addScript('officeonline', 'files');
\OCP\Util::addScript('officeonline', 'files', 'viewer');
}
);
$eventDispatcher->addListener(
'OCA\Files_Sharing::loadAdditionalScripts',
function () {
\OCP\Util::addScript('officeonline', 'files');
\OCP\Util::addScript('officeonline', 'files', 'viewer');
}
);

if (class_exists('\OC\Files\Type\TemplateManager')) {
$manager = \OC_Helper::getFileTemplateManager();

$manager->registerTemplate('application/vnd.openxmlformats-officedocument.wordprocessingml.document', dirname(__DIR__) . '/assets/docxtemplate.docx');
$manager->registerTemplate('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', dirname(__DIR__) . '/assets/xlsxtemplate.xlsx');
$manager->registerTemplate('application/vnd.openxmlformats-officedocument.presentationml.presentation', dirname(__DIR__) . '/assets/pptxtemplate.pptx');
$manager->registerTemplate('application/vnd.oasis.opendocument.presentation', dirname(__DIR__) . '/assets/template.odp');
$manager->registerTemplate('application/vnd.oasis.opendocument.text', dirname(__DIR__) . '/assets/template.odt');
$manager->registerTemplate('application/vnd.oasis.opendocument.spreadsheet', dirname(__DIR__) . '/assets/template.ods');
}

$app = \OC::$server->query(Application::class);
$app->registerProvider();
$app->updateCSP();
Binary file removed assets/docxtemplate.docx
Binary file not shown.
Binary file removed assets/pptxtemplate.pptx
Binary file not shown.
Binary file added assets/template.docx
Binary file not shown.
Binary file added assets/template.pptx
Binary file not shown.
Binary file added assets/template.xlsx
Binary file not shown.
Binary file removed assets/xlsxtemplate.xlsx
Binary file not shown.
18 changes: 3 additions & 15 deletions lib/Controller/DocumentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -542,23 +542,11 @@ public function create($mimetype,
$content = $manager->getTemplate($mimetype);
}

if (!$content) {
$content = file_get_contents(dirname(dirname(__DIR__)) . self::ODT_TEMPLATE_PATH);
}

if ($content) {
$file->putContent($content);

return new JSONResponse([
'status' => 'success',
'data' => \OCA\Files\Helper::formatFileInfo($file->getFileInfo())
]);
}

$file->putContent($content);

return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Can\'t create document')
'status' => 'success',
'data' => \OCA\Files\Helper::formatFileInfo($file->getFileInfo())
]);
}

Expand Down
4 changes: 2 additions & 2 deletions lib/TokenManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ public function getToken($fileId, $shareToken = null, $editoruid = null, $direct

try {
return [
$this->wopiParser->getUrlSrcForFile($file, $updatable)['urlsrc'], // url src might not be found ehre
$this->wopiParser->getUrlSrcForFile($file, $updatable),
$wopi->getToken(),
$wopi
];
Expand Down Expand Up @@ -264,7 +264,7 @@ public function getTokenForTemplate(File $templateFile, $userId, $targetFileId,
}

return [
$this->wopiParser->getUrlSrcForFile($targetFile, $updatable)['urlsrc'],
$this->wopiParser->getUrlSrcForFile($targetFile, $updatable),
$wopi
];
}
Expand Down
117 changes: 64 additions & 53 deletions lib/WOPI/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
use SimpleXMLElement;

class Parser {
public const ACTION_EDIT = 'edit';
public const ACTION_VIEW = 'view';
public const ACTION_EDITNEW = 'editnew';

// https://wopi.readthedocs.io/en/latest/faq/languages.html
public const SUPPORTED_LANGUAGES = [
Expand Down Expand Up @@ -146,27 +149,6 @@ public function __construct(DiscoveryManager $discoveryManager, IRequest $reques
$this->l10n = $l10n;
}

/**
* @param $mimetype
* @return array
* @throws Exception
*/
public function getUrlSrc($mimetype) {
$discoveryParsed = $this->getParsed();

$result = $discoveryParsed->xpath(sprintf('/wopi-discovery/net-zone/app[@name=\'%s\']/action', $mimetype));
if ($result && count($result) > 0) {
$urlSrc = $result[0]['urlsrc'];
$urlSrc = preg_replace('/<ui=UI_LLCC&>/', 'ui=' . $this->getLanguageCode() . '&', $urlSrc);
return [
'urlsrc' => preg_replace('/<.+>/', '', $urlSrc),
'action' => (string)$result[0]['name'],
];
}

throw new Exception('Could not find urlsrc in WOPI');
}

/**
* @return SimpleXMLElement|bool
* @throws Exception
Expand All @@ -189,45 +171,74 @@ public function getParsed() {
return $discoveryParsed;
}

/**
* @param File $file
* @param bool $edit
* @return array
* @throws Exception
*/
public function getUrlSrcForFile(File $file, $edit) {
try {
$result = $this->getUrlSrc($file->getMimeType());
return $result;
} catch (Exception $e) {
}
// FIXME: we might want to support different action types here as well like imagepreview
$actionName = $edit ? 'edit' : 'view';
$discoveryParsed = $this->getParsed();
$result = $discoveryParsed->xpath(sprintf('/wopi-discovery/net-zone[@name=\'external-https\']/app/action[@ext=\'%s\' and @name=\'%s\']', $file->getExtension(), $actionName));
if (!$result || count($result) === 0) {
$result = $discoveryParsed->xpath(sprintf('/wopi-discovery/net-zone[@name=\'external-https\']/app/action[@ext=\'%s\' and @name=\'%s\']', $file->getExtension(), 'view'));
}
public function getUrlSrcForFile(File $file, bool $edit): string {
$protocol = $this->request->getServerProtocol();
$fallbackProtocol = $protocol === 'https' ? 'http' : 'https';

if ($this->request->getServerProtocol() === 'http') {
if (!$result || count($result) === 0) {
$result = $discoveryParsed->xpath(sprintf('/wopi-discovery/net-zone[@name=\'external-http\']/app/action[@ext=\'%s\' and @name=\'%s\']', $file->getExtension(), $actionName));
}
if (!$result || count($result) === 0) {
$result = $discoveryParsed->xpath(sprintf('/wopi-discovery/net-zone[@name=\'external-http\']/app/action[@ext=\'%s\' and @name=\'%s\']', $file->getExtension(), 'view'));
$netZones = [
'external-' . $protocol,
'internal-' . $protocol,
'external-' . $fallbackProtocol,
'internal-' . $fallbackProtocol,
];

$actions = [
$edit && $file->getSize() === 0 ? self::ACTION_EDITNEW : null,
$edit ? self::ACTION_EDIT : null,
self::ACTION_VIEW,
];
$actions = array_filter($actions);

foreach ($netZones as $netZone) {
foreach ($actions as $action) {
$result = $this->getUrlSrcByExtension($netZone, $file->getExtension(), $action);
if ($result) {
return $this->replaceUrlSrcParams($result);
}
}
}
if ($result && count($result) > 0) {
$urlSrc = $result[0]['urlsrc'];
$urlSrc = preg_replace('/<ui=UI_LLCC&>/', 'ui=' . $this->getLanguageCode() . '&', $urlSrc);
return [
'urlsrc' => preg_replace('/<.+>/', '', $urlSrc),
'action' => (string)$result[0]['name'],
];

foreach ($netZones as $netZone) {
$result = $this->getUrlSrcByMimetype($netZone, $file->getMimeType());
if ($result) {
return $this->replaceUrlSrcParams($result);
}
}

throw new Exception('Could not find urlsrc in WOPI');
}

private function getUrlSrcByExtension(string $netZoneName, string $actionExt, $actionName): ?string {
$result = $this->getParsed()->xpath(sprintf(
'/wopi-discovery/net-zone[@name=\'%s\']/app/action[@ext=\'%s\' and @name=\'%s\']',
$netZoneName, $actionExt, $actionName
));

if (!$result || count($result) === 0) {
return null;
}

return (string)current($result)->attributes()['urlsrc'];
}

private function getUrlSrcByMimetype(string $netZoneName, string $mimetype): ?string {
$result = $this->getParsed()->xpath(sprintf(
'/wopi-discovery/net-zone[@name=\'%s\']/app[@name=\'%s\']/action',
$netZoneName, $mimetype
));

if (!$result || count($result) === 0) {
return null;
}

return (string)current($result)->attributes()['urlsrc'];
}

private function replaceUrlSrcParams(string $urlSrc): string {
$urlSrc = preg_replace('/<ui=UI_LLCC&>/', 'ui=' . $this->getLanguageCode() . '&', $urlSrc);
return preg_replace('/<.+>/', '', $urlSrc);
}

private function getLanguageCode(): string {
$languageCode = $this->l10n->getLanguageCode();
$localeCode = $this->l10n->getLocaleCode();
Expand Down
5 changes: 3 additions & 2 deletions src/files.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import Types from './helpers/types'
import axios from '@nextcloud/axios'
import { getCapabilities } from '@nextcloud/capabilities'
import './viewer'
import './viewer.js'
import Vue from 'vue'
import Office from './view/Office'

import './css/icons.css'
import { getCurrentDirectory } from './helpers/index.js'

// eslint-disable-next-line
__webpack_nonce__ = btoa(window.OC.requestToken)
Expand Down Expand Up @@ -60,7 +61,7 @@ const NewFilePlugin = {
},

_createDocument: function(mimetype, filename) {
const dir = document.getElementById('dir').value
const dir = getCurrentDirectory()
try {
OCA.Files.Files.isFileNameValid(filename)
} catch (e) {
Expand Down
13 changes: 13 additions & 0 deletions src/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,20 @@ const getNextcloudVersion = () => {
return parseInt(OC.config.version.split('.')[0])
}

const getCurrentDirectory = () => {
if (OCA.Sharing?.PublicApp?.fileList) {
return OCA.Sharing.PublicApp.fileList.getCurrentDirectory()
}

if (OCA?.Files?.App?.currentFileList) {
return OCA?.Files?.App?.currentFileList.getCurrentDirectory()
}

return ''
}

export {
languageToBCP47,
getNextcloudVersion,
getCurrentDirectory,
}
52 changes: 5 additions & 47 deletions src/view/Office.vue
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,13 @@
<template>
<transition name="fade" appear>
<div v-show="loading" id="officeonline-wrapper">
<div class="header">
<!-- This is obviously not the way to go since it would require absolute positioning and therefore not be compatible with viewer actions/sidebar -->
<div class="avatars">
<Avatar v-for="view in avatarViews"
:key="view.ViewId"
:user="view.UserId"
:display-name="view.UserName"
:style="viewColor(view)" />
</div>
</div>
<iframe id="officeonlineframe" ref="documentFrame" :src="src" />
</div>
</transition>
</template>

<script>
import Avatar from '@nextcloud/vue/dist/Components/Avatar'
import { getCurrentDirectory } from './../helpers/index.js'

import { getDocumentUrlForFile, getDocumentUrlForPublicFile } from '../helpers/url'
import PostMessageService from '../services/postMessage'
Expand All @@ -50,9 +40,6 @@ const PostMessages = new PostMessageService({

export default {
name: 'Office',
components: {
Avatar,
},
props: {
filename: {
type: String,
Expand All @@ -72,13 +59,9 @@ export default {
return {
src: null,
loading: false,
views: [],
}
},
computed: {
avatarViews() {
return this.views
},
viewColor() {
return view => ({
'border-color': '#' + ('000000' + Number(view.Color).toString(16)).slice(-6),
Expand All @@ -89,8 +72,8 @@ export default {
},
mounted() {
PostMessages.registerPostMessageHandler(({ parsed }) => {
console.debug('[viewer] Received post message', parsed)
const { msgId, args, deprecated } = parsed
console.debug('[viewer] Received post message', parsed, { msgId, args, deprecated })
if (deprecated) { return }

switch (msgId) {
Expand All @@ -99,20 +82,16 @@ export default {
case 'close':
this.$parent.close && this.$parent.close()
break
case 'Get_Views_Resp':
case 'Views_List':
this.views = args
break
}
})
this.load()
},
methods: {
async load() {
const sharingToken = document.getElementById('sharingToken')
const dir = document.getElementById('dir')
const dir = getCurrentDirectory()
let documentUrl = ''
if (sharingToken && dir.value === '') {
if (sharingToken && dir === '') {
documentUrl = getDocumentUrlForPublicFile(this.filename)
} else if (sharingToken) {
documentUrl = getDocumentUrlForPublicFile(this.filename, this.fileid) + '&path=' + encodeURIComponent(this.filename)
Expand All @@ -127,39 +106,18 @@ export default {
}
</script>
<style lang="scss">

.header {
position: absolute;
right: 100px;
top: -50px;

.avatars {
display: flex;
padding: 9px;

.avatardiv {
margin-left: -15px;
box-shadow: 0 0 3px var(--color-box-shadow);
}

}
}

#officeonline-wrapper {
width: 100vw;
height: calc(100vh - 50px);
left: 0;
top: 0;
position: absolute;
z-index: 100000;
max-width: 100%;
display: flex;
flex-direction: column;
background-color: var(--color-main-background);
transition: opacity .25s;

#body-public & {
position: fixed;
}
}

iframe {
Expand Down
Loading