1const Apify = require('apify');
2const humanDelay = ms => (Math.random() + 1) * ms;
3
4Apify.main(async() => {
5
6 let input = await Apify.getValue('INPUT');
7 if (!input) {
8 throw new Error('Input is missing!');
9 }
10
11 function formatDate(date) {
12 var monthNames = [
13 "January", "February", "March",
14 "April", "May", "June", "July",
15 "August", "September", "October",
16 "November", "December"
17 ];
18
19 var day = date.getDate();
20 //the invoice is for the previous month
21 var monthIndex = date.getMonth() - 1;
22 var year = date.getFullYear();
23
24 return monthNames[monthIndex] + ' ' + year;
25 }
26
27 if(input.subject.indexOf("{{date}}") !== -1){
28 input.subject = input.subject.replace("{{date}}",formatDate(new Date()));
29 }
30
31 const browser = await Apify.launchPuppeteer();
32 //Login
33 const openPage = await browser.newPage();
34 await openPage.setUserAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36.")
35
36 //go to the login page
37 console.log(`Opening URL: https://motionmailapp.com/login`);
38 await openPage.goto("https://motionmailapp.com/login");
39
40 //fill the login
41 console.log("Fill the login.")
42 await openPage.waitForSelector('input#Email');
43 const userInput = await openPage.$('input#Email');
44
45 await userInput.type(process.env.USERNAME, humanDelay(100));
46 const pwdInput = await openPage.$('input#Password');
47 await pwdInput.type(process.env.PASSWORD, {delay: humanDelay(100)});
48 //login submit
49 console.log("Login submit.")
50 await openPage.click('button[type="submit"]', {delay: humanDelay(100)});
51
52 //Wait for the dashboard
53 await openPage.waitForSelector('a[href*="billing"]')
54 await openPage.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});
55
56 //Do the post to get the invoice ids
57 console.log("We are on dashboard. Go for the latest invoice.");
58 const receipts = await openPage.evaluate(async() => {
59 return await new Promise((resolve) => {
60 $.ajax({
61 type: "POST",
62 contentType: "text/plain;charset=UTF-8",
63 url: 'https://motionmailapp.com/account/billingdata',
64 }).done(function (data, textStatus, request, xhr) {
65 console.log("data !")
66 console.log(JSON.stringify(data))
67 resolve(data.receipts)
68 }).fail(function (error) {
69 console.log("failed ajax")
70 });
71
72
73 });
74 });
75 //we have the PDF link, now go to the detail of the invoice
76 const pdfLink = "https://motionmailapp.com/account/receipt/" + receipts.pop()["id"];
77 console.log("link to the pdf -> " + pdfLink);
78 await openPage.goto(pdfLink);
79 await openPage.waitForSelector('h1')
80
81 //screenshot for debug
82 /*
83 try {
84 const screenshotBuffer = await openPage.screenshot();
85 //await Apify.setValue('screenshot', screenshotBuffer, {contentType: 'image/png'});
86 } catch (e) {
87 console.log("screenshot faild!")
88 }
89 */
90
91 //pdf file
92 const pdfBuffer = await openPage.pdf({"format": "a4",printBackground: true});
93 console.log(`Saving PDF (size: ${pdfBuffer.length} bytes) to output...`);
94 //remove comment for debug, you can download the invoice after
95 //await Apify.setValue('invoice', pdfBuffer, {contentType: 'application/pdf'});
96 await browser.close();
97
98 console.log("We have PDF, now send it.");
99
100 await Apify.call('apify/send-mail', {
101 to: input.to,
102 subject: input.subject,
103 html: input.html,
104 attachments: [{
105 filename: 'invoice.pdf',
106 data: pdfBuffer.toString('base64')
107 }]
108 });
109 //Email sent.
110 console.log("See you next month!")
111});