How to check if a file was edited/modified by a user? - file

I'm having an issue in dart/flutter, I want to check if the user opens a file and modified/edited the file, and only if this happens I do something that is not important... for that purpose I used this chunk of code:
String dir = await bloc.buildFileDirectory(filePath);
File file = new File('$dir/filename');
DateTime date = await file.lastModified();
if(date.millisecondsSinceEpoch < someOtherFileTimeStamp)
do something
with the method lastModified() from File class in Dart, when the user open the file, it will consider a modification, and so it will trigger the if condition... is there any functional way to check for really modifications on the file? like editing some text inside the file, or change the name...something like that
Ty for your time

Yes, you can use the watcher library's FileWatcher.
Here's an example on how to use it:
final watcher = FileWatcher('main.dart');
final subscription = watcher.events.listen((event) {
switch (event.type) {
case ChangeType.ADD:
print('Added file');
break;
case ChangeType.MODIFY:
print('Modified');
break;
case ChangeType.REMOVE:
print('Removed');
}
});
If you need to determine whether the file changed since last time your program ran, then this will of course not work and you will have to use the timestamp as you're doing, or even hash the contents of the file and store it somewhere, so you can check later if the hash is still the same.

Related

discord.js say command repeating message in multiple lines

So I am working on my bot, and for my ;say command I have the following code. The issue is, that when a user does something like ";say hi" it repeats as ;say on one line, goes down a line, and on that line it says hi. Before I added in a command handler, the command worked fine, however only now am I running into issues.
The code (including vars + command handler portion) -
const Prefix = require('./../../config.json');
module.exports = {
name: "say",
description: "Says the user input",
execute (Client, message, Args) {
let Say = message.content.substring(({Prefix} + 'say').Args).split(" ");
let Output = Say.splice(1);
message.channel.send(Output);
message.delete({ timeout: 1 });
},
};
in case it comes of necessity for some reason, my config.json file (might be an issue with the prefix) is in the "container" directory in the below file location -
container/commands/fun/say.js
At first, why don't you use message.content.substring(`${Prefix}say`); instead of these two lines
let Say = message.content.substring(({Prefix} + 'say').Args).split(" ");
let Output = Say.splice(1);
that would be the same, no?
I also think if you have a problem like this it's probably because there's something missing in the event handling part of your code.
Also you need to select the prefix from your config.json file, by adding .prefix or the name of your variable in your .json file after the require('./../../config.json'); not to get the entire object.

Having problems making a command that allows people to turn the blacklist on and off

I thought that allowing people to turn my blacklist on and off for their server would be kinda neat, but I didn't find much success so far. Also I was wondering, is it hard to make a command that allows people to add their own words to the blacklist? Here's the code:
let blacklisted = ['bad words here']
let foundInText = false;
for (var i in blacklisted) {
if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
message.delete();
}
});
You could use a variable for turning on or off the blacklist. BacklistOn = true, And use a if statement before the code you copied in here. Then make a command that changes that variable. You would need to store the variable in a JSON file if you want the setting to be saved when restarting the bot or if the bot crashes. Tutorial on reading/writing to JSON with node.js https://medium.com/#osiolabs/read-write-json-files-with-node-js-92d03cc82824

protractor: test download file without knowing filename

I followed this answer and it looks almost the thing I need.
The problem there is that he already knows the filename and I am doing e2e test for downloading a file, but the filename depends on the current time (even with milliseconds) so I don't really know the name (or it would be very difficult to get it).
I think I am missing something very simple here, but I was thinking of two ways:
Recreate filenames (with the same function that returns the name of this file) and start checking for existance of a file with that name, if it doesn't exist, then move to the next millisecond until I hit the right name.
Check the download folder for existance of "any" file, if I find one there then it should be the file I am downloading (for this case I don't know how to check an entire folder in protractor).
Hope you guys could help with these alternatives (I would like some help with point 2) or maybe give me a better one. Thanks
I ended up following #alecxe's suggestion and here is my answer:
var glob = require("glob");
browser.driver.wait(function () {
var filesArray = glob.sync(filePattern);
if (typeof filesArray !== 'undefined' && filesArray.length > 0) {
// this check is necessary because `glob.sync` can return
// an empty list, which will be considered as a valid output
// making the wait to end.
return filesArray;
}
}, timeout).then(function (filesArray) {
var filename = filesArray[0];
// now we have the filename and can do whatever we want
});
Just to add a little bit more background information to the #elRuLL's answer.
The main idea is based on 2 things:
browser.wait() fits the problem perfectly - it would execute a function continuously until it evaluates to true or a timeout is reached. And, the timeout mechanism is already built-in.
glob module provides a way to look for filenames matching a certain pattern (in the worst case, you can wait for the *.* - basically, any file to appear)

Haxe Asynchronously Read Local File?

I need to do IPC with another app. That app sends data and my Haxe app receives. For some reason my choice narrows down to the file system.
My idea is to have the other app keep updating a file, and my Haxe app keeps reading from that file. The problem is I keep getting the same value, although the data file is changing. I assume I need some asynchronous reader to get the updated file, but what should I use?
Here's my code:
var tmpWaveRaw = sys.io.File.getContent("assets/wave.txt");
trace(tmpWaveRaw); //always stays the same when the app is running, but changes when the app restarts.
Thanks!
Update:
Here's an experiment I just did:
Have my code keeps printing modified time of the file every 100ms.
Let the other application modify the file and stop.
Start my application. Now it's printing the correct modified time, and it is consistent with my OS's file stat.
Let the other application modify the file again. Close.
My application still prints the old modified time, not consistent with my OS's file stat.
This should work, you need to read again the file after it changes:
var running = true;
var last = sys.FileSystem.stat("test.txt");
while (running) {
var now = sys.FileSystem.stat("test.txt");
if (last.mtime.getTime() != now.mtime.getTime()) {
last = now;
trace(sys.io.File.getContent("test.txt"));
}
}

Delete avis and jpgs from a specified folder and older than x days

I want to use a script, that deletes AVIs and JPGs files from a specific folder. I want to filter them by date and extension. I have this script, which I think is really close to what I want, but it didn't deletes anything, it sends me an empty letter. (I know, I should comment out the trash parts, but it is for safety reasons so I will do it when my reports would look good)
function DeleteMyAVIs() {
var pageSize = 5000;
var files = null;
var token = null;
var i = null;
var SevenDaysBeforeNow = new Date().getTime()-3600*1000*24*7 ;
Logger.clear()
do {
var result = DocsList.getAllFilesForPaging(pageSize, token);
var files = DocsList.getFolder("motion").getFiles();
var token = result.getToken();
for(n=0;n<files.length;++n){
if(files[n].getName().toLowerCase().match('.avi')=='.avi' && files[n].getDateCreated().getTime() < SevenDaysBeforeNow){
//files[n].setTrashed(true)
Logger.log(files[n].getName()+' created on '+Utilities.formatDate(files[n].getDateCreated(), 'GMT','MMM-dd-yyyy'))
}
if(files[n].getName().toLowerCase().match('.mpg')=='.mpg' && files[n].getDateCreated().getTime() < SevenDaysBeforeNow){
//files[n].setTrashed(true)
Logger.log(files[n].getName()+' created on '+Utilities.formatDate(files[n].getDateCreated(), 'GMT','MMM-dd-yyyy'))
}
}
} while (files.length == pageSize);
MailApp.sendEmail('xy#gmail.com', 'Script AUTODELETE report', Logger.getLog());
}
You're not getting the files from the folder (it's fixed on the code below). Also, I recommend you get the folder by the id, which is a way more robust, because it allows you to rename the folder or move it inside others, and the code would still work.
Your match is also wrong (although it's not the reason it's not working), because the string will be converted into a regexp. And ".avi" would get any file with "avi" in it anywhere (aside from the very first 3 letters).
Lastly, DocsList token is not useful, because you cannot save it for a later execution, and we page not due to a Google Drive limitation, but Apps Script 6 minutes maximum execution time. In your case of deleting files, continuing the search is not really required since the files will not be there on the next search results anyway.
Lastly, when you're calling formatDate and passing GMT you're most likely going to shift the days by one, either one day before or after depending on where you are, unless you're really on GMT 0 hour and have no daylight saving shift (which I doubt). You should use your own real timezone or grab your script's default (like shown below).
function deleteMyAVIs() {
var pageSize = 500; //be careful with how much files you process at once, you're going to timeout
var sevenDaysAgo = Date.now()-1000*60*60*24*7;
var TZ = Session.getScriptTimeZone();
Logger.clear();
var result = DocsList.getFolderById('folder-id').getFilesForPaging(pageSize);
var files = result.getFiles();
//token = result.getToken(); //not useful and fortunately not important for your case
for( n=0;n<files.length;++n ) {
if(files[n].getName().toLowerCase().match('\\.(avi|mpg)$') && files[n].getDateCreated().getTime() < sevenDaysAgo){
//files[n].setTrashed(true)
Logger.log(files[n].getName()+' created on '+Utilities.formatDate(files[n].getDateCreated(), TZ,'MMM-dd-yyyy'))
}
}
MailApp.sendEmail('xy#gmail.com', 'Script AUTODELETE report', Logger.getLog());
}
By the way, if you ever require to continue a Drive search later on, you should use DriveApp instead of DocsList. Please see this other post where I show how to do it.

Resources