Search…
Providers
The first point of Aeon is making sure data is retrieved from a series of sources. These sources are abstracted into Providers. In Aeon, a Provider is a binding for a particular platform (e.g. Facebook, Instagram, LinkedIn) that can directly pull data, initiate data requests, download data and parse data.

Anatomy

Each Provider owns their own folder in src/main/providers , and may consist of several files making up two distinct elements: the Provider itself (a class that either implements Provider or DataRequestProvider), and a Parser that interprets the resulting data for visualisation. For instance, see the Instagram Provider and Instagram Parser.
The anatomy of what a Provider, Parser and datatypes look like are described in Typescript, and are available in the Provider types file. This should be a regular reference when starting to build out your own providers.

Provider

A Provider is a class that implements the bindings for a particular service. In this example we'll focus on Instagram. Each provider follows a particular workflow that covers a set of methods a platform must support: initialise, update, dispatchDataRequest, isDataRequestComplete and parseDataRequest.
Please note that a Provider distinguishes between immediately accessible data (i.e. that can be directly downloaded via an API) as updates, while data that takes a while to gather and is downloaded in one go is considered as data requests.

Initialisation

When the user wants to add an account for a certain platform, a new Provider is instantiated, and the thew initialise function is called. The point of this function is to authenticate a user to said platform, so that we can make further calls to the platform. In the case of Instagram, a very basic implementation of this looks as follows:
1
class Instagram extends Provider {
2
initialise(): Promise<boolean> {
3
return withSecureWindow<boolean>(windowParams, (window) => {
4
// Load a URL in the browser, and see if we get redirected or not
5
const profileUrl = 'https://www.instagram.com/accounts/access_tool/ads_interests';
6
window.loadURL(profileUrl);
7
8
// Create a promise that should resolve when the user is logged in
9
return new Promise((resolve) => {
10
window.webContents.on('did-navigate', () => {
11
if (profileUrl === window.webContents.getURL()) {
12
resolve();
13
}
14
});
15
});
16
});
17
}
18
}
Copied!
A BrowserWindow is opened containing a link to a protected URL. Instagram will normally redirect us to the login page, which is then shown to the user. We then wait for the login form to succeed and redirect us back to the original, protected URL. When we detect this change, the user has successfully logged in and we can return true. We can later use the cookies that are set in this instance, to send out specific requests.
Small note: you'll find that this implementation slightly differs from the actual implementation, mostly in retrieving and setting cookies relevant for later use. This is the simplest implementation, but you should find inspiration in the fully-fledged implementations that are available in the repository.

Updates

Now that we have a set of cookies, we can talk to any Instagram data as if we are the user. Fortunately, Instagram has a set of data APIs available that we can immediately gather our data from:import scrapingUrls from './urls.json';
1
import scrapingUrls from './urls.json';
2
// eg: [
3
// "https://www.instagram.com/accounts/access_tool/account_privacy_changes?__a=1",
4
// "https://www.instagram.com/accounts/access_tool/password_changes?__a=1",
5
// "https://www.instagram.com/accounts/access_tool/former_emails?__a=1",
6
// ....
7
8
class Instagram extends Provider {
9
update = async (): Promise<ProviderFile[]> => {
10
const cookies = await this.verifyLoggedInStatus();
11
12
// We extract the right cookies, and create a config we can then
13
// use for successive requests
14
const sessionid = cookies.find(cookie => cookie.name === 'sessionid').value;
15
16
// Then, we'll setup a config for each individual fetch requests
17
const fetchConfig = {
18
method: 'GET',
19
headers: {
20
Accept: 'application/json',
21
Referer: 'https://www.instagram.com/accounts/access_tool/ads_interests',
22
'X-CSRFToken': crypto.randomBytes(20).toString('hex'),
23
cookie: `sessionid=${sessionid}; shbid=${''}`
24
},
25
};
26
27
// Now we do all API requests in order to retrieve the data
28
const responses = await Promise.all(
29
scrapingUrls.map(url =>
30
fetch(url, fetchConfig).then(response => response.json())
31
)
32
);
33
34
// We then transform the data so that we can return it to the handler
35
return responses.map(response => {
36
return {
37
filepath: `${response.page_name}.json`,
38
data: JSON.stringify(response.data.data, null, 4),
39
};
40
});
41
}
42
}
Copied!
As you can see, we have a set of URLs available, and by stealing some of the cookies from the browser, we can just call all APIs, and return the data gathered from it to the ProviderManager. For this we follow the format { filepath: 'path_to_file', data: { //data } .
Note that retrieving data from APIs may not as easy with all services. If you do not want to implement immediate updates, you can return null from this function.

Dispatch Data Requests

Lots of services have an automated way of downloading your data. You click a button, wait some time, and then download a .ZIP file. Our goal is to automate the entirety of this process, starting with actually requesting the data. In our reference, Instagram has a dedicated page for these kinds of requests:
1
class Instagram extends Provider {
2
async dispatchDataRequest(): Promise<void> {
3
return withSecureWindow<void>(windowParams, async (window) => {
4
// Load the dispatched window
5
window.hide();
6
await new Promise((resolve) => {
7
window.webContents.on('did-finish-load', resolve)
8
window.loadURL('https://www.instagram.com/download/request/');
9
});
10
11
// We'll click the button for the user, but we'll need to defer to the
12
// user for a password
13
window.webContents.executeJavaScript(`
14
Array.from(document.querySelectorAll('button'))
15
.find(el => el.textContent === 'Next')
16
.click?.()
17
`);
18
window.show();
19
20
// Now we must defer the page to the user, so that they can enter their
21
// password. We then listen for a succesfull AJAX call
22
return new Promise((resolve) => {
23
window.webContents.session.webRequest.onCompleted({
24
urls: [ 'https://*.facebook.com/*' ]
25
}, (details: Electron.OnCompletedListenerDetails) => {
26
console.log('NEW REQUEST', details);
27
28
if (details.url === 'https://www.facebook.com/api/graphql/'
29
&& details.statusCode === 200) {
30
resolve();
31
}
32
});
33
});
34
});
35
}
36
}
Copied!
As you can see, Instagram requires their user so enter a password before they can send out a request. To resolve this, we present this page to the user and wait for them to enter their password. We then use particular Electron listeners to wait for the form to be submitted.

Check if Data Request is complete

It then might take a while for the data request to resolve. We currently use a polling approach to periodically check the particular page to see if the request has been completed:
1
class Instagram extends Provider {
2
async isDataRequestComplete(): Promise<boolean> {
3
return withSecureWindow<boolean>(windowParams, async (window) => {
4
// Load page URL
5
await new Promise((resolve) => {
6
window.webContents.once('did-finish-load', resolve)
7
window.loadURL('https://www.instagram.com/download/request/');
8
});
9
10
// Find a heading that reads 'Your Download is Ready'
11
return window.webContents.executeJavaScript(`
12
!!Array.from(document.querySelectorAll('h1'))
13
.find(el => el.textContent === 'Your Download is Ready');
14
`);
15
});
16
}
17
}
Copied!
This comes down to loading the page and seeing if a particular element (in this case a h1 tag reading "Your download is ready") is present on the page. This functions thus return true or false depending on whether the request is complete.

Download the Data Request

If the data request is complete, all that is left is downloading it and passing it back to Aeon. This is done as follows:
1
import { app } from 'electron';
2
import AdmZip from 'adm-zip';
3
import fs from 'fs';
4
5
const requestSavePath = path.join(app.getAppPath(), 'data');
6
7
class Instagram extends Provider {
8
async parseDataRequest(extractionPath: string): Promise<ProviderFile[]> {
9
return withSecureWindow<ProviderFile[]>(windowParams, async (window) => {
10
// Load page URL
11
await new Promise((resolve) => {
12
window.webContents.once('did-finish-load', resolve)
13
window.loadURL('https://www.instagram.com/download/request/');
14
});
15
16
await new Promise((resolve) => {
17
// Now we defer to the user to enter their credentials
18
window.webContents.once('did-navigate', resolve);
19
window.webContents.executeJavaScript(`
20
Array.from(document.querySelectorAll('button'))
21
.find(el => el.textContent === 'Log In Again')
22
.click?.()
23
`);
24
});
25
26
27
// We can now show the window for the login screen
28
window.show();
29
30
// Then we'll await the navigation back to the data download page from
31
// the login page
32
await new Promise((resolve) => {
33
window.webContents.once('will-navigate', resolve);
34
});
35
36
// We can now close the window
37
window.hide();
38
39
// Now that we're successfully authenticated on the data download page,
40
// the only thing we have to do is download the data.
41
const filePath = path.join(requestSavePath, 'instagram.zip');
42
await new Promise((resolve) => {
43
// Create a handler for any file saving actions
44
window.webContents.session.once('will-download', (event, item) => {
45
// Save the item to the data folder temporarily
46
item.setSavePath(filePath);
47
item.once('done', resolve);
48
});
49
50
// And then trigger the button click
51
window.webContents.executeJavaScript(`
52
Array.from(document.querySelectorAll('button'))
53
.find(el => el.textContent === 'Download Data')
54
.click?.()
55
`);
56
});
57
58
// We have the ZIP, all that's left to do is unpack it and pipe it to
59
// the repository
60
const zip = new AdmZip(filePath);
61
await new Promise((resolve) =>
62
zip.extractAllToAsync(extractionPath, true, resolve)
63
);
64
65
// Translate this into a form that is readable for the ParserManager
66
const files = zip.getEntries().map((entry): ProviderFile => {
67
return {
68
filepath: entry.entryName,
69
data: null,
70
};
71
});
72
73
// And dont forget to remove the zip file after it's been processed
74
await fs.promises.unlink(filePath);
75
76
return files;
77
});
78
}
79
}
Copied!
While this piece of code is a bit longer, the process is still quite simple. First, we click the download button for the user. As Instagram requires users to enter their password before downloading the file, we open the window to the user and wait for them to enter their password. We then wait for the download to be registered by the BrowserWindow, save it to a particular location, unpack it and return a list of the files that were created by this dump. Aeon will recognise this data, and create a new commit that includes all changed files from the dump.

withSecureWindow

In the reference implementations, you'll find ample use of the withSecureWindow function. This functions creates and spawns an Electron BrowserWindow for the duration of a set of requests. It returns a promise that can be returned from the callback, and rejects if an error occurs, or the user closes the window. It makes it easy to create windows a user should interact with (e.g. to log in or to manually click a button), while keeping everything secure. If you wish to keep state (i.e. cookies) between different windows, you should specify a global windowParams object that is implemented in each call to withSecureWindow.

Parsers

Now that data is actually present in the repository, we need to parse into a readable format for the front-end. We do this by means of parsers. The basic layout for a parser is as follows:
1
const parsers: ProviderParser[] = [
2
{
3
source: 'accounts_following_you.json',
4
schemas: [
5
{
6
key: 'text',
7
type: ProvidedDataTypes.FOLLOWER
8
}
9
],
10
},
11
];
Copied!
A parser is an array of files that have specific schemas attached to them. First, a new object is specified with a source: this is the filename for a particular file that is found in the repository folder for the particular Provider. Next, a schema is a mapping of a key found anywhere in that file, to a particular datatype. This means that in the file accounts_following_you.json , the schema looks for any value that is associated with the key text. This pieces of data is then associated with the FOLLOWER datatype when Aeon attempts to parse the data.
In case there isn't a neat mapping, or some data needs to be converted, a transformer can be set on the schema that interprets and transforms the data:
1
import { parseISO } from 'date-fns';
2
3
/**
4
* This specifies an input object in which the data is structured in an object,
5
* in which the keys represent usernames, and the values are ISO dates. These
6
* can be iterated upon to extract the desired data
7
*/
8
type GenericKeyedData = {
9
[key: string]: string
10
};
11
12
const parsers: ProviderParser[] = [
13
{
14
source: 'connections.json',
15
schemas: [
16
{
17
key: 'following',
18
type: ProvidedDataTypes.ACCOUNT_FOLLOWING,
19
// Transform the data from { username: '9 Jan 2011', ... } to an array of
20
// objects that store both the username and the date
21
transformer: (obj: GenericKeyedData): Partial<AccountFollowing>[] => {
22
// Loop through each available key on the object
23
return Object.keys(obj).map((key): Partial<AccountFollowing> => {
24
// Return an object in which the data is the key (username)
25
// and the timestamp is a JS Date object.
26
return {
27
data: key,
28
timestamp: parseISO(obj[key]),
29
};
30
});
31
}
32
}
33
],
34
},
35
];
Copied!
There are many more possibilities with the returned data and the transformer. Consult the ProviderParser types to see what possibilities you can use. For instance, you can also specify multiple keys for the same schema.

Registering Providers and Parsers

If you have managed to setup your own providers and parsers, the last thing that is left is registering them with Aeon. This is done in three places:
First, add the Provider class you created to the providers array in src/main/providers/index.ts. Then, add the resulting ProviderParser object to the providerParsers object in src/main/providers/parsers.ts. Lastly, add an icon for your provider to the getIcon method in src/app/utilities/Providers.ts to make sure your Provider appears pretty in the interface. Job well done!