How can I create PDF Service with a cocoa-applescript (AppleScriptObjc) application? - applescript-objc

I decided to be foolhardy and write my own Email PDF with GMail PDF service and learn AppleScriptObjC at the same time. I've got everything working, and except for actually being able to accept the file from the print dialog.
Here's what the code looks like so far:
script gmailpdfAppDelegate
property parent : class "NSObject"
property recipientField : missing value
property subjectField : missing value
property fromField : missing value
property passwordField : missing value
property messageField : missing value
property pdfFile : missing value
on ButtonHandlerCancel_(sender)
quit
end ButtonHandlerCancel_
on ButtonHandlerSend_(sender)
set recipient to recipientField's stringValue()
set subject to subjectField's stringValue()
set fromUser to fromField's stringValue()
set pw to passwordField's stringValue()
set message to messageField's stringValue()
set sendEmailScript to (current application's NSBundle's mainBundle()'s pathForResource_ofType_("sendEmail", "")) as string
set emailserverInfo to " -s smtp.gmail.com:587 -xu '" & fromUser & "' -xp '" & pw & "' -m '" & message & "' "
do shell script quoted form of sendEmailScript & " -t " & recipient & " -u " & subject & " -f '" & fromUser & "' " & emailserverInfo
quit
end ButtonHandlerSend_
on applicationWillFinishLaunching_(aNotification)
-- Insert code here to initialize your application before any files are opened
set fromField's stringValue to do shell script "defaults read org.ryancollins.GMail-PDF 'fromDefault'"
set passwordField's stringValue to do shell script "security 2>&1 >/dev/null find-generic-password -ga gmailpdf |ruby -e 'print $1 if STDIN.gets =~ /^password: \"(.*)\"$/'"
end applicationWillFinishLaunching_
on applicationShouldTerminate_(sender)
-- Insert code here to do any housekeeping before your application quits
set fromDefault to fromField's stringValue()
do shell script "defaults write org.ryancollins.GMail-PDF 'fromDefault' '" & fromDefault & "'"
set passwordDefault to passwordField's stringValue()
do shell script "security add-generic-password -a gmailpdf -s email -p '" & passwordDefault & "' -U"
return current application's NSTerminateNow
end applicationShouldTerminate_
end script
When compiled and added to the PDF Services folder I get this error (the app is named GMail PDF:
The document “Google News.pdf” could not be opened. GMail PDF cannot open files in the “Portable Document Format (PDF)” format.
How do I get an AppleScriptObjC application to accept the file?

Looks like you don't have any file-handling capabilities in your app yet, so you'll have to implement application:openFile: from NSApplicationDelegate:
From the NSApplicationDelegate documentation:
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
Which, in AppleScriptObjC, would be:
on application_openFile_(theApplication, filename)
-- your PDF handling code goes here
end application_openFile_

A simple alias of the application in the PDF Services folder should be enough to pass the PDF to the app.
Any script as a PDF Service will be sent 3 arguments: File title, job options, and path to the PDF.

Related

Unable to change the Regional format for EC2 instance via User-Data script

I am trying to change the EC2 instance's Regional format setting:
to en-GB by running Set-Culture en-GB command in my user-data script:
<powershell>
# set timezone to GMT
tzutil /s "GMT Standard Time"
# set the date format to the UK -> dd/mm/yyyy (we set it at IIS server level which would apply to all IIS apps automatically)
c:\windows\system32\inetsrv\appcmd.exe set config /commit:WEBROOT /section:globalization /culture:en-GB
c:\windows\system32\inetsrv\appcmd.exe set config /commit:WEBROOT /section:globalization /uiCulture:en-GB
# Set Regional format to UK (affects setting in Region Settings/Region/Regional format dropdown menu)
Set-Culture en-GB
</powershell>
<runAsLocalSystem>true</runAsLocalSystem>
However, when the instance boots up and I RDP to it, I find that the date format is still the default (US) - mm/dd/yyyy and not the UK format - dd/mm/yyyy
What am I missing here?
Update1
User-Data execution log:
2022/10/16 16:43:00Z: Begin user data script process.
2022/10/16 16:43:00Z: Unable to parse <persist> tags. This can happen when tags are unmatched or poorly formed.
2022/10/16 16:43:00Z: Sending telemetry bool: IsUserDataScheduledPerBoot
2022/10/16 16:43:00Z: Unregister the scheduled task to persist user data.
2022/10/16 16:43:05Z: Unable to parse <runAsLocalSystem> tags. This can happen when tags are unmatched or poorly formed.
2022/10/16 16:43:05Z: Unable to parse <script> tags. This can happen when tags are unmatched or poorly formed.
2022/10/16 16:43:05Z: Unable to parse <powershellArguments> tags. This can happen when tags are unmatched or poorly formed.
2022/10/16 16:43:05Z: <powershell> tag was provided.. running powershell content
2022/10/16 16:43:12Z: User data script completed.
2022/10/16 17:03:06Z: Begin user data script process.
2022/10/16 17:03:06Z: Failed to get metadata: The result from http://169.254.169.254/latest/user-data was empty
2022/10/16 17:03:11Z: Launch metadata did not include a user data script.
2022/10/16 17:03:11Z: User data script completed.
2022/10/20 08:27:33Z: Begin user data script process.
2022/10/20 08:27:33Z: Failed to get metadata: The result from http://169.254.169.254/latest/user-data was empty
2022/10/20 08:27:38Z: Launch metadata did not include a user data script.
2022/10/20 08:27:38Z: User data script completed.
2022/10/21 09:50:52Z: Begin user data script process.
2022/10/21 09:50:52Z: Unable to parse <persist> tags. This can happen when tags are unmatched or poorly formed.
2022/10/21 09:50:52Z: Sending telemetry bool: IsUserDataScheduledPerBoot
2022/10/21 09:50:52Z: Unregister the scheduled task to persist user data.
2022/10/21 09:50:57Z: <runAsLocalSystem> tag was provided: true
2022/10/21 09:50:57Z: Running user data as local system.
2022/10/21 09:50:57Z: Unable to parse <script> tags. This can happen when tags are unmatched or poorly formed.
2022/10/21 09:50:57Z: Unable to parse <powershellArguments> tags. This can happen when tags are unmatched or poorly formed.
2022/10/21 09:50:57Z: <powershell> tag was provided.. running powershell content
2022/10/21 09:52:36Z: Message: The errors from user data script: New-Item : An item with the specified name C:\temp already exists.
At
C:\Windows\system32\config\systemprofile\AppData\Local\Temp\Amazon\EC2-Windows\Launch\InvokeUserData\UserScript.ps1:96
char:1
+ New-Item -Path "C:\temp" -ItemType Directory
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceExists: (C:\temp:String) [New-Item], IOException
+ FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
2022/10/21 09:52:36Z: Message: The output from user data script: Join Domain User: ENR\svc_enr_domainjoin
ComputerName: EC2AMAZ-K1I0FAF
Reboot Required...
VERBOSE: Performing the operation "Join in domain 'ENR.cloud'" on target "EC2AMAZ-K1I0FAF".
HasSucceeded ComputerName
------------ ------------
True EC2AMAZ-K1I0FAF
WARNING: The changes will take effect after you restart the computer EC2AMAZ-K1I0FAF.
LocalPath : Z:
RemotePath : \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev
RequireIntegrity : False
RequirePrivacy : False
Status : OK
UseWriteThrough : False
PSComputerName :
Backing up IIS config to backup named 20221021-095225-Login
Creating virtual directories on site: Login
... Adding a virtual directory 'AnnouncementImages' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\AnnouncementImages
- Virtual directory 'IIS:\Sites\Login\AnnouncementImages' created sucessfully
... Adding a virtual directory 'apr' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\WebsiteCharts\oldAPRStructure
- Virtual directory 'IIS:\Sites\Login\apr' created sucessfully
... Adding a virtual directory 'AprSchematics' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\WebsiteCharts\apr\schematics
- Virtual directory 'IIS:\Sites\Login\AprSchematics' created sucessfully
... Adding a virtual directory 'BprDiagrams' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\WebsiteCharts\bpr\diagrams
- Virtual directory 'IIS:\Sites\Login\BprDiagrams' created sucessfully
... Adding a virtual directory 'Charts' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\WebsiteCharts
- Virtual directory 'IIS:\Sites\Login\Charts' created sucessfully
... Adding a virtual directory 'dls' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\dls
- Virtual directory 'IIS:\Sites\Login\dls' created sucessfully
... Adding a virtual directory 'Pre00CprData' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\Pre2000\cpr
- Virtual directory 'IIS:\Sites\Login\Pre00CprData' created sucessfully
... Adding a virtual directory 'Pre00DprData' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\Pre2000\dpr
- Virtual directory 'IIS:\Sites\Login\Pre00DprData' created sucessfully
... Adding a virtual directory 'Pre15BprData' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\Pre2000\bpr
- Virtual directory 'IIS:\Sites\Login\Pre15BprData' created sucessfully
... Adding a virtual directory 'WBook' for physical path \\myTeamreview_eu_dev.enr.ihsenergy.com\myTeamreview_eu_dev\Archive\Barra\live_content\wbook
- Virtual directory 'IIS:\Sites\Login\WBook' created sucessfully
Applied configuration changes to section "system.web/globalization" for "MACHINE/WEBROOT/APPHOST" at configuration commit path "MACHINE/WEBROOT"
Applied configuration changes to section "system.web/globalization" for "MACHINE/WEBROOT/APPHOST" at configuration commit path "MACHINE/WEBROOT"
PSPath : Microsoft.PowerShell.Security\Certificate::LocalMachine\my\0F006BBA30488C454380998CD818B7933
CBABB7F
PSParentPath : Microsoft.PowerShell.Security\Certificate::LocalMachine\my
PSChildName : 0F006BBA30488C454380998CD818B7933CBABB7F
PSIsContainer : False
Archived : False
Extensions : {System.Security.Cryptography.Oid, System.Security.Cryptography.Oid,
System.Security.Cryptography.Oid, System.Security.Cryptography.Oid}
FriendlyName : myTeamId
IssuerName : System.Security.Cryptography.X509Certificates.X500DistinguishedName
NotAfter : 10/21/2023 10:02:35 AM
NotBefore : 10/21/2022 9:42:35 AM
HasPrivateKey : True
PrivateKey :
PublicKey : System.Security.Cryptography.X509Certificates.PublicKey
RawData : {48, 130, 3, 42...}
SerialNumber : 3A249AE70AC9BC96464EDE49BEDD319B
SubjectName : System.Security.Cryptography.X509Certificates.X500DistinguishedName
SignatureAlgorithm : System.Security.Cryptography.Oid
Thumbprint : 0F006BBA30488C454380998CD818B7933CBABB7F
Version : 3
Handle : 1568489766128
Issuer : CN=EC2AMAZ-K1I0FAF
Subject : CN=EC2AMAZ-K1I0FAF
EnhancedKeyUsageList : {Client Authentication (1.3.6.1.5.5.7.3.2), Server Authentication (1.3.6.1.5.5.7.3.1)}
DnsNameList : {EC2AMAZ-K1I0FAF}
SendAsTrustedIssuer : False
EnrollmentPolicyEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
EnrollmentServerEndPoint : Microsoft.CertificateServices.Commands.EnrollmentEndPointProperty
PolicyId :
2022/10/21 09:52:36Z: User data script completed.

Change From Header using Mutt

I'm trying to send HTML email with an attachment using mutt. But I also have to set the From header to a custom email address. That part's not working.
Here is the command I'm trying to use:
echo $mail_body | mutt -e "set from=cloudops#noreply.company.com" -e "set content_type=text/html" -a "$ofile" -s "AWS Key Rotation Needed" -- $email_address
The HTML format, and attachment are working. How do I set the custom from header correctly?
I assume the custom email address you are speaking of is one of your configured mail accounts in mutt (account1). Simply load the corresponding configuration.
echo $mail_body | mutt -e "source ~/.mutt/accounts/account1" -e "set content_type=text/html" -a "$ofile" -s "AWS Key Rotation Needed" -- $email_address

Can't enable phar writing

I am actually using wamp 2.5 with PHP 5.5.12 and when I try to create a phar file it returns me the following message :
Uncaught exception 'UnexpectedValueException' with message 'creating archive "..." disabled by the php.ini setting phar.readonly'
even if I turn to off the phar.readonly option in php.ini.
So how can I enable the creation of phar files ?
I had this same problem and pieced together from info on this thread, here's what I did in over-simplified explanation:
in my PHP code that's generating this error, I added echo phpinfo(); (which displays a large table with all sort of PHP info) and in the first few rows verify the path of the php.ini file to make sure you're editing the correct php.ini.
locate on the phpinfo() table where it says phar.readonly and note that it is On.
open the php.ini file from step 1 and search for phar.readonly. Mine is on line 995 and reads ;phar.readonly = On
Change this line to phar.readonly = Off. Be sure that there is no semi-colon at the beginning of the line.
Restart your server
Confirm that you're phar project is now working as expected, and/or search on the phpinfo()table again to see that the phar.readonly setting has changed.
phar.readonly can only be disabled in php.ini due to security reasons.
If you want to check that it's is really not done using other method than php.ini then in terminal type this:-
$ php -r "ini_set('phar.readonly',0);print(ini_get('phar.readonly'));"
If it will give you 1 means phar.readonly is On.
More on phar.configuration
Need to disable in php.ini file
Type which php
Gives a different output depending on machine e.g.
/c/Apps/php/php-7.2.11/php
Then open the path given not the php file.
E.g. /c/Apps/php/php-7.2.11
Edit the php.ini file
could do
vi C:\Apps\php\php-7.2.11\php.ini
code C:\Apps\php\php-7.2.11\php.ini
[Phar]
; http://php.net/phar.readonly
phar.readonly = Off
; http://php.net/phar.require-hash
phar.require_hash = Off
Save
Using php-cli and a hashbang, we can set it on the fly without messing with the ini file.
testphar.php
#!/usr/bin/php -d phar.readonly=0
<?php
print(ini_get('phar.readonly')); // Must return 0
// make sure it doesn't exist
#unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->compress(Phar::GZ);
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub('<?php
function __autoload($class)
{
include "phar://myphar.phar/" . str_replace("_", "/", $class) . ".php";
}
Phar::mapPhar("myphar.phar");
include "phar://myphar.phar/startup.php";
__HALT_COMPILER();');
$p->stopBuffering();
// Test
$m = file_get_contents("phar://brandnewphar.phar/file2.txt");
$m = explode("\n",$m);
var_dump($m);
/* Output:
* there
**/
✓ Must be set executable:
chmod +x testphar.php
✓ Must be called like this:
./testphar.php
// OUTPUT there
⚠️ Must not be called like this:
php testphar.php
// Exception, phar is read only...
⚠️ Won't work called from a CGI web server
php -S localhost:8785 testphar.php
// Exception, phar is read only...
For anyone who has changed the php.ini file, but just doesn't see any changes. Try to use the CLI version of the file. For me, it was in /etc/php/7.4/cli/php.ini
Quick Solution!
Check:
cat /etc/php/7.4/apache2/php.ini | grep phar.readonly
Fix:
sed -i 's/;phar.readonly = On/;phar.readonly = Off/g' /etc/php/7.4/apache2/php.ini

Using C# program FNR to find and replace properties, file cannot be found

I have a master virtual machine with a few websites hosted on it. When I deploy a copy of this, the settings are a standard value, and I often need to change them so they fit different databases. For this I would like to use a small c# program so I can use regular expressions to find and replace whatever property needed. For this I use fnr (http://findandreplace.codeplex.com/).
findandreplace.bat:
set DATABASE="dbname"
set DBHOST="my.host.name"
set DBPORT="1234"
set ENV="this.env"
ECHO CHANGE DATABASE
"fnr" --cl --dir "D:\Inetpub\wwwroot" --fileMask "web.config" --includeSubDirectories --useRegEx --find "<add key=\"DATABASE\" value=\".*\"\s*>" --replace "<add key=\"DATABASE\" value=\"%DATABASE%\">"
ECHO CHANGE HOST
"fnr" --cl --dir "D:\Inetpub\wwwroot" --fileMask "web.config" --includeSubDirectories --useRegEx --find "<add key=\"HOST\" value=\".*\"\s*>" --replace "<add key=\"HOST\" value=\"%DBHOST%\">"
ECHO CHANGE PORT
"fnr" --cl --dir "D:\Inetpub\wwwroot" --fileMask "web.config" --includeSubDirectories --useRegEx --find "<add key=\"ConnectionString\" value=\"Data Source.*>" --replace "<add key=\"ConnectionString\" value=\"Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = %%3%%)(port = %DBPORT%)) )(CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = %%2%%)));User ID=%%0%%;Password=%%1%%;Enlist=false\">"
set /p await= "any key to continue"
Windows command prompt gives me the following output in the end:
CHANGE PORT
The system cannot find the file specified.
"any key to continue"
I can see the first two goes through and if I check the files it should touch, the values are changed correctly. I just cannot understand why the change port doesnt work, and tells me it cannot find the file specified. One, it doesnt specify any single file, and two, it looks for the same files as the first two.
Also, if I try to run the regex in FNR (the find part, with same parameters as only web.config files and in the same folder+subfolders) it finds the files perfectly.
Anyone got an idea as to what I'm doing wrong?
Thanks in advance.

Garbled text when constructing emails with vmime

Hey, my Qt C++ program has a part where it needs to send the first 128 characters or so of the output of a bash command to an email address. The output from the tty is captured in a text box in my gui called textEdit_displayOutput and put into my message I built using the Message Builder ( the object m_vmMessage ) Here is the relevant code snippet:
m_vmMessage.getTextPart()->setCharset( vmime::charsets::US_ASCII );
m_vmMessage.getTextPart()->setText( vmime::create < vmime::stringContentHandler > ( ui->textEdit_displayOutput->toPlainText().toStdString() ) );
vmime::ref < vmime::message > msg = m_vmMessage.construct();
vmime::utility::outputStreamAdapter out( std::cout );
msg->generate( out );
Giving bash 'ls /' and a newline makes vmime give terminal output like this:
ls /=0Abin etc=09 initrd.img.old mnt=09 sbin=09 tmp=09 vmlinuz.o=
ld=0Aboot farts=09 lib=09=09 opt=09 selinux usr=0Acdrom home=09 =
lost+found=09 proc srv=09 var=0Adev initrd.img media=09 root =
Whereas it should look more like this:
ls /
bin etc initrd.img.old mnt sbin tmp vmlinuz.old
boot farts lib opt selinux usr
cdrom home lost+found proc srv var
dev initrd.img media root sys vmlinuz
18:22>
Output seems to be truncated around 'root', nothing after it is displayed.
How do I encode and piece together the email properly? Does vmime just display it like that on purpose and the actual content of the email is complete and properly formatted?
Thanks!
=0A is a line feed (LF) character.
=09 is a horizontal tab (HT).
I think this is just MIME's way of encoding your non-printing (control) characters.