Skip to content

Commit

Permalink
Activate simple Nextcloud directory selector popup #96
Browse files Browse the repository at this point in the history
  • Loading branch information
the-djmaze committed Oct 19, 2022
1 parent 5abc6a3 commit f53dab1
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 65 deletions.
61 changes: 48 additions & 13 deletions plugins/nextcloud/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ public function Init() : void
$this->addHook('filter.app-data', 'FilterAppData');

$this->addJs('js/message.js');
$this->addJs('js/webdav.js');
$this->addHook('json.attachments', 'DoAttachmentsActions');
$this->addJsonHook('NextcloudSaveMsg', 'NextcloudSaveMsg');

$this->addTemplate('templates/PopupsNextcloudFiles.html');
}
}
Expand Down Expand Up @@ -60,26 +60,35 @@ public static function IsLoggedIn()

public function NextcloudSaveMsg() : array
{
$sSaveFolder = \ltrim($this->jsonParam('folder', ''), '/');
$aValues = \RainLoop\Utils::DecodeKeyValuesQ($this->jsonParam('msgHash', ''));
if (!empty($aValues['Folder']) && !empty($aValues['Uid'])) {
$aResult = [
'folder' => '',
'filename' => '',
'success' => false
];
if ($sSaveFolder && !empty($aValues['Folder']) && !empty($aValues['Uid'])) {
$oActions = \RainLoop\Api::Actions();
$oMailClient = $oActions->MailClient();
if (!$oMailClient->IsLoggined()) {
$oAccount = $oActions->getAccountFromToken();
$oAccount->ImapConnectAndLoginHelper($oActions->Plugins(), $oMailClient, $oActions->Config());
}

$sSaveFolder = $this->Config()->Get('plugin', 'save_folder', '') ?: 'Emails';
$sSaveFolder = $sSaveFolder ?: 'Emails';
$oFiles = \OCP\Files::getStorage('files');
if ($oFiles && \method_exists($oFiles, 'file_put_contents')) {
if ($oFiles) {
$oFiles->is_dir($sSaveFolder) || $oFiles->mkdir($sSaveFolder);
}
$aResult['folder'] = $sSaveFolder;

$sFilename = $sSaveFolder . '/' . ($this->jsonParam('filename', '') ?: \date('YmdHis')) . '.eml';
$aResult['folder'] = $sFilename;

$oMailClient->MessageMimeStream(
function ($rResource) use ($oFiles, $sFilename) {
function ($rResource) use ($oFiles, $sFilename, $aResult) {
if (\is_resource($rResource)) {
$oFiles->file_put_contents($sFilename, $rResource);
$aResult['success'] = $oFiles->file_put_contents($sFilename, $rResource);
}
},
(string) $aValues['Folder'],
Expand All @@ -88,15 +97,16 @@ function ($rResource) use ($oFiles, $sFilename) {
);
}

return $this->jsonResponse(__FUNCTION__, true);
return $this->jsonResponse(__FUNCTION__, $aResult);
}

public function DoAttachmentsActions(\SnappyMail\AttachmentsAction $data)
{
if (static::isLoggedIn() && 'nextcloud' === $data->action) {
$oFiles = \OCP\Files::getStorage('files');
if ($oFiles && \method_exists($oFiles, 'file_put_contents')) {
$sSaveFolder = $this->Config()->Get('plugin', 'save_folder', '') ?: 'Attachments';
$sSaveFolder = \ltrim($this->jsonParam('NcFolder', ''), '/');
$sSaveFolder = $sSaveFolder ?: $this->Config()->Get('plugin', 'save_folder', '') ?: 'Attachments';
$oFiles->is_dir($sSaveFolder) || $oFiles->mkdir($sSaveFolder);
$data->result = true;
foreach ($data->items as $aItem) {
Expand All @@ -105,14 +115,10 @@ public function DoAttachmentsActions(\SnappyMail\AttachmentsAction $data)
if (!empty($sSavedFileHash)) {
$fFile = $data->filesProvider->GetFile($data->account, $sSavedFileHash, 'rb');
if (\is_resource($fFile)) {
$sSavedFileNameFull = \MailSo\Base\Utils::SmartFileExists($sSaveFolder.'/'.$sSavedFileName, function ($sPath) use ($oFiles) {
return $oFiles->file_exists($sPath);
});

$sSavedFileNameFull = static::SmartFileExists($sSaveFolder.'/'.$sSavedFileName, $oFiles);
if (!$oFiles->file_put_contents($sSavedFileNameFull, $fFile)) {
$data->result = false;
}

if (\is_resource($fFile)) {
\fclose($fFile);
}
Expand Down Expand Up @@ -193,4 +199,33 @@ protected function configMapping() : array
->SetDefaultValue(true)
);
}

private static function SmartFileExists(string $sFilePath, $oFiles) : string
{
$sFilePath = \str_replace('\\', '/', \trim($sFilePath));

if (!$oFiles->file_exists($sFilePath)) {
return $sFilePath;
}

$aFileInfo = \pathinfo($sFilePath);

$iIndex = 0;

while (true) {
++$iIndex;
$sFilePathNew = $aFileInfo['dirname'].'/'.
\preg_replace('/\(\d{1,2}\)$/', '', $aFileInfo['filename']).
' ('.$iIndex.')'.
(empty($aFileInfo['extension']) ? '' : '.'.$aFileInfo['extension'])
;
if (!$oFiles->file_exists($sFilePathNew)) {
return $sFilePathNew;
}
if (10 < $iIndex) {
break;
}
}
return $sFilePath;
}
}
80 changes: 37 additions & 43 deletions plugins/nextcloud/js/message.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
(rl => {

function browseFiles(path = '/')
{
rl.ncFiles.getDirectoryContents(path).then(elemList => {
console.dir(elemList);
}).catch(err => console.error(err))
}

addEventListener('rl-view-model.create', e => {
if ('MailMessageView' === e.detail.viewModelTemplateID) {
let view = e.detail;
Expand All @@ -19,48 +12,49 @@
.filter(v => v);
if (hashes.length) {
view.saveNextcloudLoading(true);
rl.fetchJSON('./?/Json/&q[]=/0/', {}, {
Action: 'AttachmentsActions',
Do: 'nextcloud',
Hashes: hashes
})
.then(result => {
view.saveNextcloudLoading(false);
if (result?.Result) {
// success
} else {
view.saveNextcloudError(true);
rl.ncFiles.selectFolder().then(folder => {
if (folder) {
rl.fetchJSON('./?/Json/&q[]=/0/', {}, {
Action: 'AttachmentsActions',
Do: 'nextcloud',
Hashes: hashes,
NcFolder: folder
})
.then(result => {
view.saveNextcloudLoading(false);
if (result?.Result) {
// success
} else {
view.saveNextcloudError(true);
}
})
.catch(() => {
view.saveNextcloudLoading(false);
view.saveNextcloudError(true);
});
}
})
.catch(() => {
view.saveNextcloudLoading(false);
view.saveNextcloudError(true);
});
}
};

view.nextcloudSaveMsg = () => {
let msg = view.message();

/**
* TODO: op select screen to show browseFiles result
* Then the user can select which Nextcloud folder to save to
*/
// browseFiles();

rl.pluginRemoteRequest(
(iError, data) => {
console.dir({
iError:iError,
data:data
});
},
'NextcloudSaveMsg',
{
'msgHash': msg.requestHash,
'filename': msg.subject()
}
);
rl.ncFiles.selectFolder().then(folder => {
let msg = view.message();
folder && rl.pluginRemoteRequest(
(iError, data) => {
console.dir({
iError:iError,
data:data
});
},
'NextcloudSaveMsg',
{
'msgHash': msg.requestHash,
'folder': folder,
'filename': msg.subject()
}
);
});
};
}
});
Expand Down
43 changes: 38 additions & 5 deletions plugins/nextcloud/js/webdav.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,21 +96,54 @@
});
}

onShow(files, fResolve) {
onBuild(dom) {
this.tree = dom.querySelector('#sm-nc-files-tree');
this.tree.addEventListener('click', event => {
let li = event.target.closest('li');
if (li.item_name) {
this.close();
this.fResolve(li.item_name);
}
});
}

// Happens after showModal()
beforeShow(files, fResolve) {
this.files(!!files);
this.fResolve = fResolve;
}

select() {
this.close();
this.fResolve(this.folder());
this.tree.innerHTML = '';
fetchFiles(propertyRequestBody, '/').then(items => {
items.forEach(item => {
if (item.isFile) {
if (files) {
// TODO show files
}
} else {
let li = document.createElement('li'),
a = document.createElement('a');
li.item_name = item.name;
a.append('- ' + item.name.replace(/^\/+/, ''));
li.append(a);
this.tree.append(li);
}
});
}).catch(err => console.error(err))
}

onClose() {
this.close();
this.fResolve();
return false;
}
/*
onShow() {} // Happens after showModal()
beforeShow() {} // Happens before showModal()
afterShow() {} // Happens after showModal() animation transitionend
onHide() {} // Happens before animation transitionend
afterHide() {} // Happens after animation transitionend
close() {}
*/
}

rl.ncFiles = new class {
Expand Down
2 changes: 2 additions & 0 deletions plugins/nextcloud/langs/en.ini
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[NEXTCLOUD]
SAVE_ATTACHMENTS = "Save in Nextcloud"
SAVE_EML = "Save as .eml in Nextcloud"
SELECT_FOLDER = "Select folder"
SELECT_FILES = "Select file(s)"
9 changes: 5 additions & 4 deletions plugins/nextcloud/templates/PopupsNextcloudFiles.html
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<header>
<a class="close" href="#" data-bind="click: close">×</a>
<h3 data-i18n="NEXTCLOUD/BROWSE"></h3>
<h3 data-i18n="NEXTCLOUD/SELECT_FOLDER" data-bind="hidden:files"></h3>
<h3 data-i18n="NEXTCLOUD/SELECT_FILES" data-bind="visible:files"></h3>
</header>
<div class="modal-body form-horizontal">
<!--
TODO: built tree of directories and optional files
In case of directories: radiobutton to select one OR click selects
In case of files: checkbox to select (multiple)
-->
<ul id="sm-nc-files-tree"></ul>
</div>
<footer>
<a class="btn" data-bind="command: select" data-i18n="NEXTCLOUD/SELECT"></a>
</footer>

0 comments on commit f53dab1

Please sign in to comment.