Node.js on the Fidonet site: automation of periodical publications

  • Tutorial
Some fidoshniks are faced with the need to periodically publish the same message (the same text file) every few days in a particular Fidonet echoconference.

For example, a moderator (or a moderator, depending on the distribution of their duties) has to put her rules into his echo-conference once a week or two . A slightly different (but still similar) example is those fidos, who have taken upon themselves the support of some FAQ and also publish it in one or more thematically relevant echo conferences. (In the echo of Fidonet.History, its FAQ contains a peculiar annals of the history of Fidonet, expressed in questions and answers, in the echo of SU.IP.Point - a list of nodes gaining new points in SU.FidoTech -clarification of a number of technical terms and algorithms of several useful techniques. In echoconferences dedicated to a particular software product, the FAQ explains how to configure it. And so on.)

If the node (or point) runs continuously on the same computer, then such publication is automated in a simple, ingenuous way: publish the file to the list of tasks for the cron daemon (on UNIX-like systems) or its analogue in other systems.

Если же фидонетовская система работает не на одном и том же компьютере (есть ведь фидошники, которые с одного рабочего места на другое таскали с собою комплект фидонетовского софта некогда на дискете, а в новейшее время таскают на флэшке) или хотя бы работает не беспрерывно (а запускается фидошником время от времени, когда в нём рождается желание отправить, получить и почитать фидопочту), то регулярность публикаций обеспечивается иначе — не сервисом (демоном), а простой программою, которая проверяет, не прошло ли ещё столько дней со времени последней публикации файла, сколько необходимо для того, чтобы настало время вдругорядь опубликовать его.

Сегодня мы рассмотрим, каким подспорьем может движок Node.js стать в исполнении этой задачи.

First of all, we note that a significant part of this problem has already been solved.

In order to publish a file, just give the hpt post command to the HPT echo processor from the Husky software suite . (Similar commands exist in some other popular Fidonet echo processors.)

In order to save (remember) the date and time of such publication, it is enough to issue the touch command in relation to some file, updating the date of its last change. UNIX-like operating systems usually contain this command in a ready-made form, and for Windows it can be downloaded from the unxutils site on SourceForge.

Therefore, it remains to compose only a team that would perform the opposite task - it would allow the command line to read the age of the specified file, expressed in days, as well as compare it with some specified age. And for this purpose, we’ll use the following JavaScript for Node.js:

var fs = require('fs');
var clog = console.log;
if (process.argv.length < 3) {
   clog('Usage:');
   clog('   node agedays "filename" [N]');
   clog('');
   clog('Parameters:');
   clog('   filename     -- name of the file which age (in days) is checked');
   clog('   N (optional) -- if file is N days old (or older),');
   clog('                   errorlevel 1 is set');
} else if (process.argv.length == 3) {
   try {
      var msec = (new Date()).getTime() -
         fs.statSync(process.argv[2]).mtime.getTime();
      var days = msec / 1000 / 60 / 60 / 24;
      clog('File "' + process.argv[2] + '" is ' + days + ' days old.');
   } catch(e) {
      clog('File "' + process.argv[2] + '" cannot be opened.');
   }
} else {
   try {
      var msec = (new Date()).getTime() -
         fs.statSync(process.argv[2]).mtime.getTime();
      var days = msec / 1000 / 60 / 60 / 24;
      if( days > (+process.argv[3]) ) {
         process.exit(1);
      } else {
         process.exit(0);
      }
   } catch(e) {
      clog('File "' + process.argv[2] + '" cannot be opened.');
      process.exit(2);
   }
}

Having saved this script and named it agedays.js , we get the opportunity to run it to find out the age of the file and to compare this age with a predetermined number. Here is an example of such actions in Windows on the file areas.cfg:

[agedays screenshot]

Adding such a tool to two previously available (to the echo processor and touch ), we finally get the opportunity to compose a batch file (file with operating system commands), which will perform the task of periodically publishing one or more files in Fidonet. Here is an example of the batch file that is used on my site under Windows:

@echo off
:checkmonth
node agedays NodePost\monthly._flag 30
if errorlevel 1 goto monthly
goto checkweek
:monthly
\utils\unxutils\touch NodePost\monthly._flag
hpt post -nf "Mithgol's Wishlist Robot" -s "Список желаемых функций Голдеда" -e "Ru.GoldEd" -z "Mithgol's NodePost" -o "FGHI Global Headlight Ignited" -f loc NodePost\GED_Wish.txt
goto checkweek
:checkweek
node agedays NodePost\weekly._flag 7
if errorlevel 1 goto weekly
goto end
:weekly
\utils\unxutils\touch NodePost\weekly._flag
hpt post -nf "Moderator of Ru.Fidonet.Yo" -s "*** Rules" -e "Ru.Fidonet.Yo" -z "Mithgol's NodePost" -o "FGHI Global Headlight Ignited" -f loc NodePost\YoRulez.txt
hpt post -nf "Moderator of Ru.Russophobia" -s "*** Rules" -e "Ru.Russophobia" -z "Mithgol's NodePost" -o "FGHI Global Headlight Ignited" -f loc NodePost\PhobRule.txt
hpt post -nf "Moderator of Ru.Russian.1916" -s "*** Rules" -e "Ru.Russian.1916" -z "Mithgol's NodePost" -o "FGHI Global Headlight Ignited" -f loc NodePost\rule1916.txt
goto end
:end

Such a batch file (in my example it is called NodePost.cmd ) is most conveniently located in the same directory as HPT and run from there: this allows the hpt post command to find the HPT configuration file in its working directory. I put the files published by the batch file in a subdirectory called NodePost; flags files are also located there , their sole purpose is to be touched by the touch command and checked by the agedays command .

You can see in the source code that this batch file provides monthly (every thirty days) publication of one file in Ru.GoldED, as well as weekly (every seven days) distribution of three files with the rules for the three Fidonet echo conferences on behalf of the moderator (" Moderator of ... ").

The command lines beginning with the words “hpt post” are long enough and will probably be automatically wrapped when they are displayed on Habrahabr, but in reality each such command is written in one line. (To prevent them from merging with neighboring teams after such a transfer, I added one empty line at the top and bottom of each hpt post command for clarity.) After the “-nf” parameterthe sender’s name is written, under which the file will be sent to the echo conference, and after the “-e” parameter - the echo tag of this echo conference. After the parameters “-s”, “-z” and “-o” , the desired message header, its tearline and origin are recorded. The “-f loc” parameter is absolutely necessary for the message to be considered “local” (created precisely at this Fidonet station) and subsequently be packed by the echo processor as outgoing to other Fidonet nodes. The final parameter is the name of the file being published.

(If instead of the popular HPT you use a different echo processor in Fidonet, then all this information will allow you to easily replace the “hpt post” with a call to a command more suitable for your software.)

Most of the elements of the above solution (Node.js engine, agedays script, touch command, HPT echo processor) are also multi-system (cross-platform), so when you transfer it from Windows to another operating system, you only have to rewrite the batch file. I posted the

script agedays.js on Github under a free MIT license, and this is the end of my story.

Also popular now: