Mailspring/internal_packages/link-tracking/lib/link-tracking-composer-extension.es6
Drew Regitsky fe7a894e51 feat(new-plugins): add open tracking and link tracking plugins
Summary:
Adds two (very similar) plugins - Open Tracking and Link Tracking.
Both can be enabled via a button in the composer. Open tracking
inserts a tracking pixel right before send, and link tracking replaces
all links with tracked redirects. Both plugins use the new Metadata
service to store their open/click counts, and have backend servers to
respectively serve the pixel image or handle the redirects. Requests
also trigger a metadata update to increment the open/click counters.

Test Plan: Manual for now

Reviewers: evan, bengotow, drew

Reviewed By: bengotow

Differential Revision: https://phab.nylas.com/D2583
2016-02-19 12:42:56 -08:00

46 lines
1.7 KiB
JavaScript

import {ComposerExtension, Actions, QuotedHTMLTransformer} from 'nylas-exports';
import plugin from '../package.json'
import uuid from 'node-uuid';
const LINK_REGEX = (/(<a\s.*?href\s*?=\s*?")([^"]*)("[^>]*>)|(<a\s.*?href\s*?=\s*?')([^']*)('[^>]*>)/g);
const PLUGIN_ID = plugin.appId;
const PLUGIN_URL = "n1-link-tracking.herokuapp.com";
class DraftBody {
constructor(draft) {this._body = draft.body}
get unquoted() {return QuotedHTMLTransformer.removeQuotedHTML(this._body);}
set unquoted(text) {this._body = QuotedHTMLTransformer.appendQuotedHTML(text, this._body);}
get body() {return this._body}
}
export default class LinkTrackingComposerExtension extends ComposerExtension {
static finalizeSessionBeforeSending({session}) {
const draft = session.draft();
// grab message metadata, if any
const metadata = draft.metadataForPluginId(PLUGIN_ID);
if (metadata) {
const draftBody = new DraftBody(draft);
const links = [];
const messageUid = uuid.v4().replace(/-/g, "");
// loop through all <a href> elements, replace with redirect links and save mappings
draftBody.unquoted = draftBody.unquoted.replace(LINK_REGEX, (match, prefix, url, suffix) => {
const encoded = encodeURIComponent(url);
const redirectUrl = `http://${PLUGIN_URL}/${draft.accountId}/${messageUid}/${links.length}?redirect=${encoded}`;
links.push({url: url, click_count: 0, click_data: []});
return prefix + redirectUrl + suffix;
});
// save the draft
session.changes.add({body: draftBody.body});
session.changes.commit();
// save the link info to draft metadata
metadata.uid = messageUid;
metadata.links = links;
Actions.setMetadata(draft, PLUGIN_ID, metadata);
}
}
}