"use strict";
const EXPORTED_SYMBOLS = ["core", "resources"];
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
const resources = {
browser: {
styles: ["/native/fx/bindings.css"]}};
const WIDGET_NAME = "http://bar.yandex.ru/packages/yandexbar#mail";
const core = {
Settings: {
getMainTemplate: function MailWidgetSettings_getMainTemplate(aWidgetUnitName, aWidgetInstanceId) {
var prefsXULPath = "native/fx/mail/preferences.xul";
var prefsScriptPath = "native/fx/preferences/preferences.js";
var api = core._api;
var xulStream = api.Package.getFileInputChannel(prefsXULPath).contentStream;
var strXUL = api.StrUtils.readStringFromStream(xulStream);
xulStream.close();
var scriptStream = api.Package.getFileInputChannel(prefsScriptPath).contentStream;
var strScript = api.StrUtils.readStringFromStream(scriptStream);
scriptStream.close();
return strXUL.replace("{{SCRIPT}}",strScript);
}
},
init: function MailWidget_init(api) {
this._api = api;
this._logger = api.logger;
this._currentNotifications = {
};
this._pkgRootURL = api.Package.resolvePath("/");
this._loadModules();
this.dauth.addListener(this.dauth.EVENTS.AUTH_STATE_CHANGED,this);
}
,
finalize: function MailWidget_finalize() {
if (this._showNotificationTimer)
this._showNotificationTimer.cancel();
delete this._showNotificationTimer;
delete this._currentNotifications;
this.dauth.removeListener(this.dauth.EVENTS.AUTH_STATE_CHANGED,this);
delete this._pkgRootURL;
delete this.utils;
delete this._api;
delete this._logger;
delete this.__stringBundle;
}
,
buildWidget: function MailWidget_buildWidget(WIID, item) {
item.setAttribute("yb-native-widget-name",WIDGET_NAME);
item.setAttribute("yb-native-widget-wiid",WIID);
item.module = this;
if (this.dauth.authorized)
this._createInstSlice(WIID);
}
,
destroyWidget: function MailWidget_destroyWidget(WIID, item, context) {
try {
if (typeof item.destroy == "function")
item.destroy();
this.dlgman.closeAlertDialog("mail");
}
 finally {
item.removeAttribute("yb-native-widget-name");
item.removeAttribute("yb-native-widget-wiid");
}

}
,
onNoMoreInstProjections: function MailWidget_onNoMoreInstProjections(WIID) {
this._destroyInstSlice(WIID);
}
,
get API() this._api,
mailto: function MailWidget_mailto(event, mailAddress) {
var strMailURL = this.getYaMailURL();
var statAction = this._STAT_CODES.MAIL_TO;
var user = this.dauth.user;
if (user && ! user.domainIsMain)
{
strMailURL = this.getMFDMailURL() + "for/" + user.domain + "/";
statAction = this._STAT_CODES.MAIL_TO_MFD;
}

var mailURL = strMailURL + "compose?mailto=" + encodeURIComponent(mailAddress.replace(/^mailto\:/,""));
this._navigateToMailURL(mailURL,statAction,event);
}
,
onButtonClick: function MailWidget_onButtonClick(event, widget) {

}
,
refreshData: function MailWidget_refreshData(event, callback) {

}
,
sendPageToYaMail: function MailWidget_sendPageToYaMail(event) {
var url = this.getYaMailURL() + "compose";
this._sendPage(url,this._STAT_CODES.GOTO_SEND_PAGE,event);
}
,
sendPageToMFDMail: function MailWidget_sendPageToMFDMail(strDomain, event) {
var url = this.getYaMailURL() + "for/" + strDomain + "/compose";
this._sendPage(url,this._STAT_CODES.GOTO_MFD_SEND_PAGE,event);
}
,
_navigateToMailURL: function MailWidget__navigateToMailURL(strMailURL, statAction, origEvent) {
if (statAction)
this.API.Statistics.logShortAction(statAction);
this.API.Controls.navigateBrowser({
url: strMailURL,
eventInfo: origEvent});
}
,
getPref: function MailWidget_getPref(strPrefName, defaultValue) {
return this._api.Settings.getValue(strPrefName);
}
,
setPref: function MailWidget_setPref(strPrefName, strPrefValue) {
this._api.Settings.setValue(strPrefName,strPrefValue);
}
,
observe: function MailWidget_observe(aSubject, aTopic, aData) {
switch (aTopic) {
case this.dauth.EVENTS.AUTH_STATE_CHANGED:
if (this.dauth.authorized)
{
this.API.Controls.getAllWidgetItems().forEach(function (item) {
item._button && item._button._updateCounterText(this.counterValue);
this._createInstSlice(item.getAttribute("yb-native-widget-wiid"));
}
,this);
}
 else
{
this.counterValue = 0;
this.API.Controls.getAllWidgetItems().forEach(function (item) {
item._button && item._button._updateCounterText(this.counterValue);
this._destroyInstSlice(item.getAttribute("yb-native-widget-wiid"));
}
,this);
}

this._notifySlices({
message: aData.hasAuth ? "user.login" : "user.logout",
data: this._makeUsersDataForNotification([aData.user])});
break;
}

}
,
_makeUsersDataForNotification: function MailWidget__makeUsersDataForNotification(users) {
var auth = this.dauth;
var yandexuid = auth.yauth.getYandexCookie("yandexuid",false);
var passportDomain = auth.authdefs.DOMAINS.MAIN_DOMAIN;
return users.map(function (user) {
return {
id: yandexuid,
login: user.login,
type: user.type,
domain: user.domain,
passport: passportDomain,
authorized: user.authorized,
social: auth.authdefs.USER_TYPES.USER_FOREIGN == user.type ? user.authProvider : ""};
}
);
}
,
mailSlices: Object.create(null),
_makeSliceURL: function MailWidget__makeSliceURL(WIID) {
return this._pkgRootURL + "native/fx/mail/slice/mail.html";
}
,
_notifySliceAboutAllUsers: function MailWidget__notifySliceAboutAllUsers() {
var users = [];
try {
users = users.concat(this.dauth.liveUsers);
}
catch (e) {
return false;
}

this._notifySlices({
message: "user.get_all",
data: this._makeUsersDataForNotification(users)});
}
,
_notifySliceAboutActiveUsers: function MailWidget__notifySliceAboutActiveUsers() {
this._notifySlices({
message: "user.get_all",
data: this._makeUsersDataForNotification(this.dauth.users)});
}
,
_logoutUsers: function MailWidget__logoutUsers(users) {
users.forEach(function (user) {
this.dauth.initLogoutProcess(user.name,false);
}
,this);
}
,
counterValue: 0,
_messageHandler: function MailWidget__messageHandler(aMessage) {
switch (aMessage.message) {
case "messages.unread_count":
this.counterValue = aMessage.data;
this.API.Controls.getAllWidgetItems().forEach(function (item) {
item._button._updateCounterText(aMessage.data);
}
);
break;
case "messages.new":
{
if (this.getPref("showTextAlert",true))
this._showNotification(aMessage.data);
let isSoundAlertEnabled = this.API.Environment.barPlatform.soundsEnabled && this.getPref("playSoundAlert",false);
if (isSoundAlertEnabled)
{
let strURI = this.getPref("soundURI");
if (strURI)
this.utils.playSound(strURI);
}

break;
}

case "user.get_all":
this._notifySliceAboutAllUsers();
break;
case "user.get_active":
this._notifySliceAboutActiveUsers();
break;
case "user.logout":
{
let user = this.dauth.getUserForDomain(aMessage.data.domain);
if (user)
this._logoutUsers([user]);
break;
}

case "user.logout_all":
{
this._logoutUsers(this.dauth.users);
break;
}

case "user.login":
{
let {login: login, domain: domain} = aMessage.data;
let user;
if (login && domain)
{
this.dauth.liveUsers.some(function (liveUser) {
if (liveUser.login == login && liveUser.domain == domain)
{
user = liveUser;
return true;
}

return false;
}
);
}

if (user && user.password)
{
this.dauth.initLoginProcess(user.fullNameForPassManager,user.password,true);
}
 else
{
if (login || domain)
this._logger.error("Can't find user with saved password for {login: '" + login + "', domain: '" + domain + "''}");
let topBrowser = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator).getMostRecentWindow("navigator:browser");
if (! topBrowser)
return;
let widget = topBrowser.document.querySelector("[yb-native-widget-name='" + WIDGET_NAME + "']") || this.API.Controls.getAllWidgetItems()[0];
if (! widget)
return;
user = user || this.dauth.yauth.createUser(login + "@" + domain,null,false);
let dialogParams = {
name: "mail",
title: widget.getAttribute("title"),
login: user && user.fullNameForPassManager};
let onCloseCallback = (function onCloseCallback() {

}
).bind(this);
this.dauth.openAuthDialog({
target: widget},dialogParams,false,onCloseCallback);
}

break;
}

}

}
,
_createInstSlice: function MailWidget__createInstSlice(WIID) {
if (this.mailSlices[WIID])
return;
this.mailSlices[WIID] = this.API.Controls.createSlice({
url: this._makeSliceURL(WIID),
messageHandler: this._messageHandler},WIID);
}
,
_destroyInstSlice: function MailWidget__destroyInstSlice(WIID) {
var slice = this.mailSlices[WIID];
if (slice)
{
slice.destroy();
delete this.mailSlices[WIID];
}

}
,
_notifySlices: function MailWidget__notifySlices(aData) {
for each(let slice in this.mailSlices) slice.notify(aData);
}
,
get _MAIL_HOST() {
var mailHost = this._api.Localization.createStringBundle("/urls/mail.properties").get("MailHost");
delete this._MAIL_HOST;
return this._MAIL_HOST = mailHost;
}
,
_MAX_UNREAD_MAIL: 30,
_STAT_CODES: {
GOTO_SEND_PAGE: 1050,
GOTO_MFD_SEND_PAGE: 1055,
CLICK_ON_ALERT: 11,
CLICK_ON_MULTI_ALERT: 12,
MAIL_TO: 1021,
MAIL_TO_MFD: 1022,
SHARE_CONTENT: 1050},
_MODULES: {
utils: "utils.jsm",
dauth: "yauth.jsm",
dlgman: "dlgman.jsm"},
_loadModules: function MailWidget__loadModules() {
var shAPI = this._api.shareableAPI;
for each(let [moduleName, moduleFileName] in Iterator(this._MODULES)) {
Cu.import(this._api.Package.resolvePath("/native/fx/modules/" + moduleFileName),this);
let module = this[moduleName];
if (typeof module.init == "function")
module.init(shAPI);
}

}
,
__stringBundle: null,
get _stringBundle() {
return this.__stringBundle || (this.__stringBundle = this._api.Localization.createStringBundle("/native/fx/mail.properties"));
}
,
getYaMailURL: function MailWidget_getYaMailURL() {
return "https://" + this._MAIL_HOST + "/";
}
,
getMFDMailURL: function MailWidget_getMFDMailURL() {
return this.getYaMailURL();
}
,
_currentNotifications: null,
_showNotificationTimer: null,
_lastShowedTime: 0,
_showNotification: function MailWidget__showNotification(aMessagesData) {
var inboxURL = aMessagesData.inbox_url.replace(/(:\/\/mail\.yandex\.)[^\/]+\//,"$1ru/");
var notifications = this._currentNotifications[inboxURL];
if (notifications)
{
notifications.messages = notifications.messages.concat(aMessagesData.messages);
}
 else
{
this._currentNotifications[inboxURL] = aMessagesData;
}

this._showNextNotification();
}
,
_showNextNotification: function MailWidget__showNextNotification() {
if (this._showNotificationTimer)
{
this._showNotificationTimer.cancel();
this._showNotificationTimer = null;
}

var topBrowserWindow = this.dlgman.getTopBrowserWindow();
var isFullScreen = topBrowserWindow && topBrowserWindow.fullScreen;
if (isFullScreen || Math.abs(Date.now() - this._lastShowedTime) < 10000)
{
let notify = (function MailWidget__showNextNotification_notify() this._showNextNotification()).bind(this);
let timeout = isFullScreen ? 3 * 60000 : 1000;
this._showNotificationTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._showNotificationTimer.initWithCallback({
notify: notify},timeout,Ci.nsITimer.TYPE_ONE_SHOT);
return;
}

var inboxURL = null;
for(let url in this._currentNotifications) {
if (! this._currentNotifications[url].messages.length)
delete this._currentNotifications[url]; else
inboxURL = url;
}

if (! inboxURL)
return;
this._lastShowedTime = Date.now();
var notification = this._currentNotifications[inboxURL];
if (! notification)
return;
var badgeCounter = notification.messages.length;
this.dlgman.openAlertDialog("mail",this.API,{
url: notification.inbox_url,
urlAction: badgeCounter > 1 ? this._STAT_CODES.CLICK_ON_MULTI_ALERT : this._STAT_CODES.CLICK_ON_ALERT,
serviceTitle: this._stringBundle.get("mailNotificationTitle"),
badgeCounter: badgeCounter,
badgeText: this._stringBundle.getPlural("mailNotificationMsg",[badgeCounter]),
messages: notification.messages});
notification.messages = [];
this._showNextNotification();
}
,
_getBuildMailURL: function MailWidget__getBuildMailURL(strDomain) {
if (! /^yandex\.(\w){2,3}$/.test(strDomain))
return this.getMFDMailURL() + "for/" + strDomain + "/message?ids=";
return this.getYaMailURL() + "message?ids=";
}
,
_sendPage: function MailWidget__sendPage(strURL, statAction, origEvent) {
var currentWindow = this.utils.getCurrentWindow();
var dataToSend = {
body: this.utils.getDocumentDescription(currentWindow.content.document) + currentWindow.content.location.href,
subject: currentWindow.content.document.title};
var strParams = "subject=" + encodeURIComponent(dataToSend.subject.substr(0,1000000)) + "&body=" + encodeURIComponent(dataToSend.body.substr(0,1000000));
if (strParams.length > 8192 && /^https?:\/\/mail\.yandex\./.test(strURL))
{
strURL = strURL.replace("/compose?","/classic/compose?");
}

var stringStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
stringStream.setData(strParams,strParams.length);
var postData = Cc["@mozilla.org/network/mime-input-stream;1"].createInstance(Ci.nsIMIMEInputStream);
postData.addHeader("Content-Type","application/x-www-form-urlencoded");
postData.addContentLength = true;
postData.setData(stringStream);
if (statAction)
this.API.Statistics.logShortAction(statAction);
this.API.Controls.navigateBrowser({
target: "new tab",
url: strURL,
eventInfo: origEvent,
postData: postData});
}
,
shareContent: function MailWidget_shareContent(shareData, event) {
const LINE_BREAK = "\n\n";
const srcChromeWnd = event.target.ownerDocument.defaultView;
const sharedDoc = srcChromeWnd.content.document;
var dataToSend = {
body: "",
subject: "",
url: ""};
var pageAddress = srcChromeWnd.content.location.href;
var srcLine = this._stringBundle.get("sendContentSource",[pageAddress + LINE_BREAK]);
switch (shareData.contentType) {
case "SharePage":
{
dataToSend.url = pageAddress;
dataToSend.subject = sharedDoc.title;
let sharedDocDescr = this._getDescriptionMeta(sharedDoc);
if (sharedDocDescr)
dataToSend.body = sharedDocDescr + LINE_BREAK;
dataToSend.body += pageAddress;
break;
}

case "ShareSelection":
{
let imgHintTemplate = this._stringBundle.get("sendImageTemplate");
dataToSend.body = srcLine + this.utils.getSelectionString(srcChromeWnd,imgHintTemplate);
break;
}

case "ShareImage":
{
let imgData = shareData.image;
if (imgData)
{
dataToSend.body = srcLine + "<img src=\"" + imgData.imageURL + "\" " + "alt=\"" + (imgData.imageName || imgData.imageURL) + "\" " + "title=\"" + imgData.imageName + "\" " + "/>";
dataToSend.message_type = "html";
}

break;
}

}

this._send(this.getYaMailURL() + "compose?mailto=",dataToSend);
}
,
_send: function YaruWidget__send(url, dataToSend) {
var postParams = [];
for(let [paramName, paramValue] in Iterator(dataToSend)) {
if (paramName && paramValue)
postParams.push(paramName + "=" + encodeURIComponent(paramValue.substr(0,1000000)));
}

postParams = postParams.join("&");
var postStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
postStream.setData(postParams,postParams.length);
var postData = Cc["@mozilla.org/network/mime-input-stream;1"].createInstance(Ci.nsIMIMEInputStream);
postData.addHeader("Content-Type","application/x-www-form-urlencoded");
postData.addContentLength = true;
postData.setData(postStream);
this.API.Controls.navigateBrowser({
url: url,
target: "new tab",
postData: postData});
this.API.Statistics.logShortAction(this._STAT_CODES.SHARE_CONTENT);
}
,
_getDescriptionMeta: function MailWidget__getDescriptionMeta(doc) {
var metaElements = doc.getElementsByTagName("meta");
for (let i = 0, len = metaElements.length;i < len;i++) {
let metaElement = metaElements[i];
let metaName = (metaElement.name || "").toLowerCase();
if (metaName == "description" && metaElement.content)
return metaElement.content;
}

return null;
}
};
