Is there a way in deployd to map a collection to a different endpoint? - deployd

I have a collection called customer_devices and I can't change the name. Can I expose it via deployd as /devices ? How?

There are a few ways that I can think of. If you really just want to rename the collection, you can do so from the dashboard, as #thomasb mentioned in his answer.
Alternatively, you can create a "proxy" event resource devices and forward all queries to customer_devices. For example, in devices/get.js you would say
dpd.customer_devices.get(query, function(res, err) {
if (err) cancel(err);
setResult(res);
});
Update
Finally, here is a "hack" to redirect all requests from one resource path to a different path. This is poorly tested so use at your own risk. This requires that you set up your own server as explained here. Once you have that, you can modify the routing behaviour using this snippet:
server.on('listening', function() {
var customer_devices = server.router.resources.filter(function (res) {
return res.path === '/customer_devices';
})[0];
// Make a copy of the Object's prototype
var devices = Object.create(customer_devices);
// Shallow copy the properties
devices = extend(devices, customer_devices);
// Change the routing path
devices.path = "/devices";
// Add back to routing cache
server.router.resources.push(devices);
});
This will take your customer_devices resource, copy it, change the path, and re-insert it into the cached routing table. I tested it and it works, but I won't guarantee that it's safe or a good idea...

Can't you change the name via dashboard?
Mouseover your collection customer_devices
Click the down arrow
Select 'Rename'
Enter the new name and click 'Rename'

Related

TYPO3 - Retrieved TypoScript in itemsProcFunc are incomplete

I have following problem:
We are overriding the tt_content TCA with a custom column which has an itemsProcFunc in it's config. In the function we try to retrieve the TypoScript-Settings, so we can display the items dynamically. The problem is: In the function we don't receive all the TypoScript-Settings, which are included but only some.
'itemsProcFunc' => 'Vendor\Ext\Backend\Hooks\TcaHook->addFields',
class TcaHook
{
public function addFields($config){
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$configurationManager = $objectManager->get('TYPO3\\CMS\\Extbase\\Configuration\\ConfigurationManagerInterface');
$setup = $configurationManager->getConfiguration(
\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT
);
}
$setup is now incomplete and doesn't contain the full TypoScript, for example some of the static-included TypoScript is missing.
Used TYPO3 7 LTS (7.6.18), PHP 7.0.* in composer-mode.
Does anybody know where the problem is? Is there some alternative?
You maybe misunderstood the purpose of TypoScipt. It is a way of configuration for the Frontend. The Hook you mentioned is used in the TCA, whích is a Backend part of TYPO3. TypoScript usually isn't used for backend related stuff at all, because it is bound to a specific page template record. Instead in the backend, there is the TSConfig, that can be bound to a page, but also can be added globally. Another thing you are doing wrong is the use of the ObjectManager and the ConfigurationManager, which are classes of extbase, which isn't initialized in the backend. I would recommend to not use extbase in TCA, because the TCA is cached and loaded for every page request. Instead use TSConfig or give your configuration settings directly to the TCA. Do not initialize extbase and do not use extbase classes in these hooks.
Depending on what you want to configure via TypoScript, you may want to do something like this:
'config' => [
'type' => 'select',
'renderType' => 'singleSelect',
'items' => [
['EXT:my_ext/Resources/Private/Language/locallang_db.xlf:myfield.I.0', '']
],
'itemsProcFunc' => \VENDOR\MyExt\UserFunctions\FormEngine\TypeSelectProcFunc::class . '->fillSelect',
'customSetting' => 'somesetting'
]
and then access it in your class:
class TypeSelectProcFunc{
public function fillSelect(&$params){
if( $params['customSetting'] === 'somesetting' ){
$params['items'][] = ['New item',1];
}
}
}
I had a similar problem (also with itemsProcFunc and retrieving TypoScript). In my case, the current page ID of the selected backend page was not known to the ConfigurationManager. Because of this it used the page id of the root page (e.g. 1) and some TypoScript templates were not loaded.
However, before we look at the solution, Euli made some good points in his answer:
Do not use extbase configuration manager in TCA functions
Use TSconfig instead of TypoScript for backend configuration
You may like to ask another question what you are trying to do specifically and why you need TypoScript in BE context.
For completeness sake, I tested this workaround, but I wouldn't recommend it because of the mentioned reasons and because I am not sure if this is best practice. (I only used it because I was patching an extension which was already using TypoScript in the TCA and I wanted to find out why it wasn't working. I will probably rework this part entirely.)
I am posting this in the hope that it may be helpful for similar problems.
public function populateItemsProcFunc(array &$config): array
{
// workaround to set current page id for BackendConfigurationManager
$_GET['id'] = $this->getPageId((int)($config['flexParentDatabaseRow']['pid'] ?? 0));
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$configurationManager = $objectManager->get(BackendConfigurationManager::class);
$setting = $configurationManager->getTypoScriptSetup();
$templates = $setting['plugin.']['tx_rssdisplay.']['settings.']['templates.'] ?? [];
// ... some code removed
}
protected function getPageId(int $pid): int
{
if ($pid > 0) {
return $pid;
}
$row = BackendUtility::getRecord('tt_content', abs($pid), 'uid,pid');
return $row['pid'];
}
The function getPageId() was derived from ext:news which also uses this in an itemsProcFunc but it then retrieves configuration from TSconfig. You may want to also look at that for an example: ext:news GeorgRinger\News\Hooks\ItemsProcFunc::user_templateLayout
If you look at the code in the TYPO3 core, it will try to get the current page id from
(int)GeneralUtility::_GP('id');
https://github.com/TYPO3/TYPO3.CMS/blob/90fa470e37d013769648a17a266eb3072dea4f56/typo3/sysext/extbase/Classes/Configuration/BackendConfigurationManager.php#L132
This will usually be set, but in an itemsProcFunc it may not (which was the case for me in TYPO3 10.4.14).

API to modify Firefox downloads list

I am looking to write a small firefox add-on that detects when files that were downloaded are (or have been) deleted locally and removes the corresponding entry in the firefox download list.
Can anybody point me to the relevant api to manipulate the download list? I cannot seem to find it.
The relevant API is PlacesUtils which abstracts the complexity of the Places database.
If your code runs in the context of a chrome window then you get a PlacesUtils glabal variable for free. Otherwise (bootstrapped, Add-on SDK, whatever) you have to import PlacesUtils.jsm.
Cu.import("resource://gre/modules/PlacesUtils.jsm");
As far as Places is concerned, downloaded files are nothing more than a special kind of visited pages, annotated accordingly. It's a matter of just one line of code to get an array of all downloaded files.
var results = PlacesUtils.annotations.getAnnotationsWithName("downloads/destinationFileURI");
Since we asked for the destinationFileURI annotation, each element of the resultarray holds the download location in the annotationValue property as a file: URI spec string.
With that you can check if the file actually exists
function getFileFromURIspec(fileurispec){
// if Services is not available in your context Cu.import("resource://gre/modules/Services.jsm");
var filehandler = Services.io.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler);
try{
return filehandler.getFileFromURLSpec(fileurispec);
}
catch(e){
return null;
}
}
getFileFromURIspec will return an instance of nsIFile, or null if the spec is invalid which shouldn't happen in this case but a sanity check never hurts. With that you can call the exists() method and if it returns false then the associated page entry in Places is eligible for removal. We can tell which is that page by its uri, which conveniently is also a property of each element of the results.
PlacesUtils.bhistory.removePage(result.uri);
To sum it up
var results = PlacesUtils.annotations.getAnnotationsWithName("downloads/destinationFileURI");
results.forEach(function(result){
var file = getFileFromURIspec(result.annotationValue);
if(!file){
// I don't know how you should treat this edge case
// ask the user, just log, remove, some combination?
}
else if(!file.exists()){
PlacesUtils.bhistory.removePage(result.uri);
}
});

dart HTMLrequest default to index.html does not work

I have a simple Dart HTTPServer running which serves requests by virDir.serveRequest(request); which works for the URL 192.168.1.200:8080/index.html but serves a 404 Not Found if I use 192.168.1.200:8080 or 192.168.1.200:8080/. I, probably naively, though that the default was automatic. BTW this is all new to me.
I didn't notice any default settings in HTMLServer, how is this accomplished?
(edit)
I've been able to detect the use using the default and compute the correct file name but don't understand how to deliver it to the browser:
_processRequest(newPath, request) { // new path is index.html
File file = new File(newPath);
file.exists().then((found) {
if(found) {
file.openRead().pipe(request.response); // probably dies here
}
else {
_send404(request.response);
}
});
}
[edit]
Still unable to serve the index.html file. I've tried using VirtualDirector.serveFile() but can't make it work when I try to handle the default index.html file. I've been attempting to follow an example.
final HTTP_ROOT_PATH = Platform.script.resolve('../web').toFilePath();
final virDir = new VirtualDirectory(HTTP_ROOT_PATH)
..jailRoot = false // process links will work
..followLinks = true
..allowDirectoryListing = true;
var dir = new Directory(virDir.root);
var indexUri = new Uri.file(dir.path).resolve('/index.html');
virDir.serveFile(new File(indexUri.toFilePath()), request);
When I run this and print indexUri.toFilePath() the output is '/index.html'
My code is in /srv/fireimager/bin and /srv/fireimager/web with the latter the virtual directory root. When I detect that the user has not specified /index.html in the url it doesn't work, there's no error emitted, and the javascript console shows nothing so nothing is served to the browser.
I obviously don't understand how to use VirtualDirectly.serveFiler.
Your default page or index.html is not assumed by your browser but by the server.
What you will want to do is check to see what your request ends with. In my server, I check to see if it ends with a "/". If it does end with a "/", I open and send my default page.
Also, you will want to make sure you check your request to make sure it's not trying to access areas it it not suppose to. Check for ".." in your path segments. If you have any, you probably want to kill the connection.

IBM Worklight 6.0 - Pass parameter to JSONStore load function

I want to load a JSONStore based on a provided param to the adapter mapped load function.
Let me explain it better.
The JSONStore initialization is like this:
collections[EMPLOYEE_COLLECTION_NAME] = {
searchFields : {ENAME: 'string', EMPNO:'integer'},
//-- Start optional adapter metadata
adapter : {
name: 'EmployeesDB',
add: 'addEmployee',
remove: 'deleteEmployee',
replace: 'updateEmployee',
load: {
procedure: 'getEmployee',
params: [region],
key: 'resultSet'
}
}
//-- End optional adapter metadata
};
//Initialize the people collection
WL.JSONStore.init(collections, options)
As you can see in the code above, even after the param region was passed to the adapter collection init, is it supposed to change during my app life cycle, so there are moments where region let's say is SOUTH, others is NORTH and so on.
I realized that even though I change this value after the store was created, the mapped load function in the adapter getEmployee (see below) always get value that region contained at the time the jsonstore was initialized regardless I change the region variable value later on. Looks like the adapter binds conf is getting at collection creation time, and never changes it
function getEmployee(data) {
WL.Logger.info('Show param:'+data);
return WL.Server.invokeSQLStatement({
preparedStatement : selectStatement,
parameters : []
});
}
Is there a way to pass parameter to the Jsonstore load function that can change after the store was initialized ?
I wanted to avoid close and init the collection again to save time and resources.
By the way, what I really need is to have flexibility on what I load from the database based on a adapter parameter that is bound to a collection.
Try something like:
WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).adapter.load.params = ['...']
Before calling WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).load().
If you want more flexibility, you can always call WL.Client.invokeProcedure and inside the onSuccess callback you can call: WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).add(['...'], {push: false}). The push: false section will make sure JSONStore understands that the data added is up-to-date with the data on the backend. This means it won't show those documents when you call: WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).getPushRequired() or WL.JSONStore.get(EMPLOYEE_COLLECTION_NAME).push().

Create tab/window with DOM document instead of URI?

I have a web service that requires special headers to be sent in the request. I am able to retrieve expected responseXMLs using an XMLHttpRequest and setRequestHeader().
Now I would like to create a new tab (or window) containing the response document. I would like the default XMLPrettyPrint.xsl file applied to it and when the source is viewed, I'd like to see the un-styled source as when viewing a normal .xml file.
Any ideas?
I ended up creating a protocol handler.
The biggest trick that I didn't find to be documented well was the fact that the XPCOM contract ID must start with "#mozilla.org/network/protocol;1?name=". E.g.,:
/* as in foo:// . This is called the scheme. */
var thisIsWhatMyProtocolStartsWith = "foo";
var contractID = "#mozilla.org/network/protocol;1?name=" + thisIsWhatMyProtocolStartsWith;

Resources