///
// Variable to store the ShareOperation object
var shareOperation = null;
var TYPE_IMAGE = 0;
var TYPE_QUOTE = 1;
var TYPE_LINK = 2;
var shareType;
var imageBase64;
var shareArgs;
var asyncPropsToLoad = [];
function activatedHandler(eventArgs) {
Windows.Storage.ApplicationData.current.addEventListener('datachanged', updateForPublishing);
shareArgs = eventArgs;
document.getElementById("publish-quote").addEventListener("click", publishPost, false);
document.getElementById("publish-link").addEventListener("click", publishPost, false);
document.getElementById("publish-image").addEventListener("click", publishPost, false);
document.getElementById("follow-blog").addEventListener("click", followUnfollowBlog, false);
document.getElementById("unfollow-blog").addEventListener("click", followUnfollowBlog, false);
if (!WPCom.isLoggedIn()) {
WPCom.signInOut();
return;
}
// setShareLayout();
loadAsyncProps();
}
function loadAsyncProps() {
if (shareArgs.kind !== Windows.ApplicationModel.Activation.ActivationKind.shareTarget)
return; // Nothing to see here citizen. Move along.
var asyncOperations = [];
// We receive the ShareOperation object as part of the eventArgs
shareOperation = shareArgs.shareOperation;
// Fetch async values.
if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.bitmap)) {
asyncPropsToLoad['image'] = { loading: true, result: null };
asyncOperations.push(function () {
shareOperation.data.getBitmapAsync().then(function (result) {
asyncPropsToLoad['image'].loading = false;
asyncPropsToLoad['image'].result = result;
onAsyncPropsLoaded();
});
});
} else {
if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.text)) {
asyncPropsToLoad['text'] = { loading: true, result: null };
asyncOperations.push(function () {
shareOperation.data.getTextAsync().then(function (result) {
asyncPropsToLoad['text'].loading = false;
asyncPropsToLoad['text'].result = result;
onAsyncPropsLoaded();
});
});
};
if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.uri)) {
asyncPropsToLoad['uri'] = { loading: true, result: null };
asyncOperations.push(function () {
shareOperation.data.getUriAsync().then(function (result) {
asyncPropsToLoad['uri'].loading = false;
asyncPropsToLoad['uri'].result = result
onAsyncPropsLoaded();
});
});
};
};
// Trigger the async ops.
for (var key in asyncOperations) {
asyncOperations[key]();
};
};
function onAsyncPropsLoaded() {
// Wait for all the things to load.
for (var key in asyncPropsToLoad) {
if (asyncPropsToLoad[key].loading) {
return;
};
};
// For now, image trumps the rest
if (typeof asyncPropsToLoad['image'] != 'undefined') {
shareType = TYPE_IMAGE;
} else {
if (typeof asyncPropsToLoad['text'] != 'undefined') {
var text = asyncPropsToLoad['text'].result;
var isURI = false;
try {
Windows.Foundation.Uri(text);
isURI = true;
} catch (e) { };
if (isURI) {
shareType = TYPE_LINK;
} else {
shareType = TYPE_QUOTE;
};
};
if (typeof asyncPropsToLoad['uri'] != 'undefined') {
if (shareType != TYPE_QUOTE) {
shareType = TYPE_LINK;
};
};
};
switch (shareType) {
case TYPE_IMAGE:
setShareBitmapLayout();
break;
case TYPE_LINK:
setShareLinkLayout();
break;
case TYPE_QUOTE:
setShareQuoteLayout();
break;
default:
break;
};
};
function setShareBitmapLayout() {
WPCom.toggleElement(document.getElementById("shareImage"), 'show');
updateForPublishing();
if (shareOperation.data.properties.title)
document.getElementById("shareImageTitle").value = shareOperation.data.properties.title;
if (shareOperation.data.properties.description)
document.getElementById("shareImageCaption").value = shareOperation.data.properties.description;
var streamRef = asyncPropsToLoad['image'].result;
streamRef.openReadAsync().then(function (imageStream) {
if (imageStream) {
var reader = new Windows.Storage.Streams.DataReader(imageStream);
var promise = reader.loadAsync(imageStream.size).then(function (readSize) {
var buffer = reader.readBuffer(readSize);
imageBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
}, function (result) {
// TODO: Error
});
var fullimageBlob = MSApp.createBlobFromRandomAccessStream(imageStream.contentType, imageStream);
var fullimagelUrl = URL.createObjectURL(fullimageBlob, false);
document.getElementById("fullimageImage").src = fullimagelUrl;
};
});
};
function setShareQuoteLayout() {
var url = null;
var text = asyncPropsToLoad['text'].result;
var title = shareOperation.data.properties.title;
WPCom.toggleElement(document.getElementById("shareQuote"), 'show');
updateForPublishing();
document.getElementById("shareQuoteText").value = text;
// A uri might be included with the quote so check for it.
if (asyncPropsToLoad['uri']) {
url = asyncPropsToLoad['uri'].result.absoluteUri;
document.getElementById("shareQuoteURL").value = uri;
} else {
var description = shareOperation.data.properties.description;
if (description.substring(0, 4) == 'http') {
};
};
if (!url) {
var description = shareOperation.data.properties.description;
if (description.substring(0, 4) == 'http') {
url = description;
};
};
if (url) {
// We have a url so let's use it with our title.
if (!title) { // No title? Use the url.
title = url;
};
// Try to get the title from the page itself.
WinJS.xhr({
type: "GET",
url: url
}).then(function (result) {
// Grab the title if it exists
var matchedTitle = result.responseText.match(/.*
(.*)<\/title>.*/)[1];
if (matchedTitle) {
title = matchedTitle;
};
document.getElementById("shareQuoteURL").value = '' + title + '';
}, function (result) {
// Called failed, so use the default title.
document.getElementById("shareQuoteURL").value = '' + title + '';
});
} else {
// Default title.
document.getElementById("shareQuoteURL").value = title;
};
};
function setShareLinkLayout() {
var url = asyncPropsToLoad['uri'].result.absoluteUri;
var title = shareOperation.data.properties.title;
// Apps like the Maps app will have the app uri as the uri result,
// and the web uri as the text result. Check for this, and
// if there is a url in the text, favor it.
if (typeof asyncPropsToLoad['text'] != 'undefined') {
var text = asyncPropsToLoad['text'].result;
if (text.indexOf('http') == 0 && url.indexOf("http") != 0) {
try {
var textUri = Windows.Foundation.Uri(text);
url = textUri.absoluteUri;
} catch (e) { };
};
};
WPCom.toggleElement(document.getElementById("shareLink"), 'show');
updateForPublishing();
document.getElementById("shareLinkURL").value = url;
if (title) {
document.getElementById("shareLinkDescription").value = title;
};
// If this is not an http link don't try to do a look up.
if (url.indexOf('http') != 0) {
return;
};
// Check if it is a valid site and show the Follow/Unfollow buttons
var progress = document.getElementById("publish-progress");
progress.style.display = "block";
// We need to load the real URL of the site here. Otherwise shorlinks like wp.me/38jh3 do not work out of the box.
document.getElementById("followStatusText").innerText = "Loading subscription status...";
WPCom.toggleElement(document.getElementById("follow-blog"), 'hide');
WPCom.toggleElement(document.getElementById("unfollow-blog"), 'hide');
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'show');
WinJS.xhr({
type: "GET",
url: url
}).then(function (result) {
var site_url;
var matches = result.responseText.match(/]+\>/);
if (matches && matches.length > 1) {
site_url = matches[1];
} else {
//we can't check the subscription status for the current site.
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'hide');
progress.style.display = "none";
return;
};
//prepare the REST call
var accessToken = WPCom.getCurrentAccessToken();
var blogID = site_url.replace(/^http:\/\//, '').replace(/^https:\/\//, '');
blogID = blogID.substring(0, blogID.indexOf('/'));
blogID = encodeURIComponent(WPCom.stripTrailingSlash(blogID));
//remember the site info.
document.getElementById("follow-blog-title").value = 'http://' + blogID; //Just the site URL for now. Unfortunately the 'title' tag is not so useful, since it contains the title of the article and other stuff in it.
document.getElementById("follow-blog-uri").value = blogID;
var url = WPCom.apiURL + "/sites/" + blogID + "/follows/mine";
WinJS.xhr({
type: "GET",
url: url,
headers: { "Authorization": "Bearer " + accessToken }
}).then(function (result) {
progress.style.display = "none";
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'show');
var resultData = JSON.parse(result.responseText);
if (resultData.is_following) {
//already following the blog
document.getElementById("followStatusText").innerText = "You're already following '" + document.getElementById("follow-blog-title").value + "'";
WPCom.toggleElement(document.getElementById("follow-blog"), 'hide');
WPCom.toggleElement(document.getElementById("unfollow-blog"), 'show');
} else {
//not following the blog
document.getElementById("followStatusText").innerHTML = "You're not following '" + document.getElementById("follow-blog-title").value + "'. You can add it to your Reader by clicking the button below.";
WPCom.toggleElement(document.getElementById("follow-blog"), 'show');
WPCom.toggleElement(document.getElementById("unfollow-blog"), 'hide');
}
}, function (result) {
//var resultData = JSON.parse(result.responseText);
//resultData.message
document.getElementById("followStatusText").innerText = "Sorry, a network error occurred. We can't read the subscription status for " + uri.absoluteUri + ". Please try again later.";
progress.style.display = "none";
});
}, function (result) {
//error on the first HTTP GET
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'hide');
progress.style.display = "none";
});
}
function setShareLayout() {
if (shareArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.shareTarget) {
// We receive the ShareOperation object as part of the eventArgs
shareOperation = shareArgs.shareOperation;
// Display the data received based on data type
if (shareOperation.data.properties.thumbnail) {
//load the thumbnail if one was provided
shareOperation.data.properties.thumbnail.openReadAsync().then(function (thumbnailStream) {
var thumbnailBlob = MSApp.createBlobFromRandomAccessStream(thumbnailStream.contentType, thumbnailStream);
var thumbnailUrl = URL.createObjectURL(thumbnailBlob, false);
document.getElementById("thumbnailImage").src = thumbnailUrl;
document.getElementById("thumbnailArea").style.display = "block";
});
}
if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.bitmap)) {
//Let's share an image!
shareType = TYPE_IMAGE;
WPCom.toggleElement(document.getElementById("shareImage"), 'show');
updateForPublishing();
if (shareOperation.data.properties.title)
document.getElementById("shareImageTitle").value = shareOperation.data.properties.title;
if (shareOperation.data.properties.description)
document.getElementById("shareImageCaption").value = shareOperation.data.properties.description;
shareOperation.data.getBitmapAsync().then(function (streamRef) {
streamRef.openReadAsync().then(function (imageStream) {
if (imageStream) {
var reader = new Windows.Storage.Streams.DataReader(imageStream);
var promise = reader.loadAsync(imageStream.size).then(function (readSize) {
var buffer = reader.readBuffer(readSize);
imageBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
}, function (result) {
// error
});
var fullimageBlob = MSApp.createBlobFromRandomAccessStream(imageStream.contentType, imageStream);
var fullimagelUrl = URL.createObjectURL(fullimageBlob, false);
document.getElementById("fullimageImage").src = fullimagelUrl;
}
});
});
}
if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.text)) {
// Let's share a quote!
if (shareType != TYPE_IMAGE) {
shareType = TYPE_QUOTE;
WPCom.toggleElement(document.getElementById("shareQuote"), 'show');
updateForPublishing();
shareOperation.data.getTextAsync().then(function (text) { document.getElementById("shareQuoteText").value = text; });
var pageUrl = shareOperation.data.properties.description;
var pageTitle;
if (pageUrl.substring(0, 4) == 'http') {
WinJS.xhr({
type: "GET",
url: pageUrl
}).then(function (result) {
pageTitle = result.responseText.match(/.*(.*)<\/title>.*/)[1];
if (!pageTitle) {
pageTitle = pageUrl;
}
document.getElementById("shareQuoteURL").value = '' + pageTitle + '';
}, function (result) {
pageTitle = pageUrl;
document.getElementById("shareQuoteURL").value = '' + pageTitle + '';
});
} else {
document.getElementById("shareQuoteURL").value = shareOperation.data.properties.title;
}
}
}
if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.uri)) {
shareOperation.data.getUriAsync().then(function (uri) {
if (shareType == TYPE_QUOTE) {
document.getElementById("shareQuoteURL").value = uri.absoluteUri;
}
else if (shareType != TYPE_IMAGE) {
//let's share a link!
WPCom.toggleElement(document.getElementById("shareLink"), 'show');
updateForPublishing();
document.getElementById("shareLinkURL").value = uri.absoluteUri;
if (shareOperation.data.properties.title)
document.getElementById("shareLinkDescription").value = shareOperation.data.properties.title;
//Check if it is a valid site and show the Follow/Unfollow buttons
var progress = document.getElementById("publish-progress");
progress.style.display = "block";
//we need to load the real URL of the site here. Otherwise shorlinks like wp.me/38jh3 do not work out of the box.
document.getElementById("followStatusText").innerText = "Loading subscription status...";
WPCom.toggleElement(document.getElementById("follow-blog"), 'hide');
WPCom.toggleElement(document.getElementById("unfollow-blog"), 'hide');
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'show');
WinJS.xhr({
type: "GET",
url: uri.absoluteUri
}).then(function (result) {
var matches = result.responseText.match(/]+\>/);
if (matches && matches.length > 1) {
var site_url = matches[1];
} else {
//we can't check the subscription status for the current site.
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'hide');
progress.style.display = "none";
return;
}
//prepare the REST call
var accessToken = WPCom.getCurrentAccessToken();
var blogID = site_url.replace(/^http:\/\//, '').replace(/^https:\/\//, '');
blogID = blogID.substring(0, blogID.indexOf('/'));
blogID = encodeURIComponent(WPCom.stripTrailingSlash(blogID));
//remember the site info.
document.getElementById("follow-blog-title").value = 'http://' + blogID; //Just the site URL for now. Unfortunately the 'title' tag is not so useful, since it contains the title of the article and other stuff in it.
document.getElementById("follow-blog-uri").value = blogID;
var url = WPCom.apiURL + "/sites/" + blogID + "/follows/mine";
WinJS.xhr({
type: "GET",
url: url,
headers: { "Authorization": "Bearer " + accessToken },
}).then(function (result) {
progress.style.display = "none";
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'show');
var resultData = JSON.parse(result.responseText);
if (resultData.is_following) {
//already following the blog
document.getElementById("followStatusText").innerText = "You're already following '" + document.getElementById("follow-blog-title").value + "'";
WPCom.toggleElement(document.getElementById("follow-blog"), 'hide');
WPCom.toggleElement(document.getElementById("unfollow-blog"), 'show');
} else {
//not following the blog
document.getElementById("followStatusText").innerHTML = "You're not following '" + document.getElementById("follow-blog-title").value + "'. You can add it to your Reader by clicking the button below.";
WPCom.toggleElement(document.getElementById("follow-blog"), 'show');
WPCom.toggleElement(document.getElementById("unfollow-blog"), 'hide');
}
}, function (result) {
//var resultData = JSON.parse(result.responseText);
//resultData.message
document.getElementById("followStatusText").innerText = "Sorry, a network error occurred. We can't read the subscription status for " + uri.absoluteUri + ". Please try again later.";
progress.style.display = "none";
});
}, function (result) {
//error on the first HTTP GET
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'hide');
progress.style.display = "none";
});
}
});
} //
}
}
function publishPost(m) {
var button = m.currentTarget;
var progress = document.getElementById("publish-progress");
progress.style.display = "block";
WPCom.toggleElement(document.getElementById("followBlogDiv"), 'hide');
button.value = "Publishing...";
var content;
var data = new FormData();
//grab the form values TODO: add validation (empty fields, etc)
if (button.id == "publish-image") {
if (imageBase64) {
//upload the image via xmlrpc first
var accessToken = WPCom.getCurrentAccessToken();
var timestamp = new Date().getTime() + ".jpg";
var xmlrpcURL = "http://" + WPCom.getCurrentBlogURL() + "/xmlrpc.php";
var xmlString = 'wp.uploadFile1usernamepasswordtypeimage/jpegoverwrite1bits' + imageBase64 + 'name' + timestamp + '';
WinJS.xhr({
type: "POST",
url: xmlrpcURL,
headers: { "Authorization": "Bearer " + accessToken },
data: xmlString
}).then(function (result) {
var xmlDoc = result.responseXML;
var values = xmlDoc.getElementsByTagName("string");
var imageURL;
for (var i = 0; i < values.length; i++) {
//look for the image URL
if (values[i].textContent.indexOf("http://") >= 0) {
imageURL = values[i].textContent;
}
}
if (imageURL) {
//if we have an image url, build out the post content
var imageTitle = document.getElementById("shareImageTitle").value;
var imageLink = document.getElementById("shareImageURL").value;
var imageCaption = document.getElementById("shareImageCaption").value;
var imageWidth = document.getElementById("fullimageImage").naturalWidth;
content = '';
if (imageLink)
content = '' + content + '';
if (imageCaption)
content = '[caption id="" width="' + imageWidth + '" caption="' + imageCaption + '"]' + content + '[/caption]';
if (imageTitle.length > 25) {
data.append("title", imageTitle.substring(0, 25) + "...");
} else {
data.append("title", imageTitle);
}
data.append("format", "image");
data.append("content", content);
createNewPost(data, button);
}
else {
document.getElementById("errorMessage").innerText = "Sorry, a network error occurred. Please try again later.";
progress.style.display = "none";
button.value = "Publish";
}
}, function (result) {
document.getElementById("errorMessage").innerText = "Sorry, a network error occurred. Please try again later.";
progress.style.display = "none";
button.value = "Publish";
});
}
}
else if (button.id == "publish-quote") {
var quoteText = document.getElementById("shareQuoteText").value;
var quoteURL = document.getElementById("shareQuoteURL").value;
if (quoteText) {
content = "
" + quoteText + "
";
}
if (quoteURL) {
content += "\n\n" + quoteURL + "\n\n";
}
if (quoteText.length > 25) {
data.append("title", quoteText.substring(0, 25) + "...");
} else {
data.append("title", quoteText);
}
data.append("format", "quote");
data.append("content", content);
createNewPost(data, button);
} else {
var linkURL = document.getElementById("shareLinkURL").value;
var linkDescription = document.getElementById("shareLinkDescription").value;
var linkComment = document.getElementById("shareLinkComment").value;
if (linkDescription)
content = "" + linkDescription + "";
else
content = "" + linkURL + "";
if (linkComment)
content = content + "\n\n" + linkComment + "\n\n";
data.append("format", "link");
data.append("content", content);
createNewPost(data, button);
}
}
function createNewPost(data, button) {
var accessToken = WPCom.getCurrentAccessToken();
var blogID = WPCom.getCurrentBlogID();
var progress = document.getElementById("publish-progress");
if (!blogID) {
document.getElementById("errorMessage").innerText = "Sorry, an error occurred.";
return;
}
var url = WPCom.apiURL + "/sites/" + blogID + "/posts/new";
WinJS.xhr({
type: "POST",
url: url,
headers: { "Authorization": "Bearer " + accessToken },
data: data
}).then(function (result) {
var resultData = JSON.parse(result.responseText);
if (resultData.ID)
reportCompleted();
else {
document.getElementById("errorMessage").innerText = "Sorry, a network error occurred. Please try again later.";
progress.style.display = "none";
button.value = "Publish";
}
}, function (result) {
document.getElementById("errorMessage").innerText = "Sorry, a network error occurred. Please try again later.";
progress.style.display = "none";
button.value = "Publish";
});
}
function reportError() {
document.getElementById("errorMessage").innerText = "The sharing operation enountered an error. Please try again.";
}
function reportCompleted() {
shareOperation.reportCompleted();
}
// Initialize the activation handler
Windows.UI.WebUI.WebUIApplication.addEventListener("activated", activatedHandler);
function updateForPublishing(e) {
var message;
if (WPCom.isLoggedIn()) {
message = "Publishing to " + WPCom.getCurrentBlogURL();
if (WinJS.Utilities.hasClass(document.getElementById('shareImage'), 'show')) {
WPCom.toggleElement(document.getElementById('publish-image'), 'show');
document.getElementById("imageBlogName").innerHTML = message;
} else if (WinJS.Utilities.hasClass(document.getElementById('shareLink'), 'show')) {
WPCom.toggleElement(document.getElementById('publish-link'), 'show');
document.getElementById("linkBlogName").innerHTML = message;
} else if (WinJS.Utilities.hasClass(document.getElementById('shareQuote'), 'show')) {
WPCom.toggleElement(document.getElementById('publish-quote'), 'show');
document.getElementById("quoteBlogName").innerHTML = message;
}
} else {
message = 'Sign in to WordPress.com to publish this post.';
if (WinJS.Utilities.hasClass(document.getElementById('shareImage'), 'show')) {
WPCom.toggleElement(document.getElementById('publish-image'), 'hide');
WinJS.Utilities.setInnerHTMLUnsafe(document.getElementById('imageBlogName'), message);
} else if (WinJS.Utilities.hasClass(document.getElementById('shareLink'), 'show')) {
WPCom.toggleElement(document.getElementById('publish-link'), 'hide');
WinJS.Utilities.setInnerHTMLUnsafe(document.getElementById('linkBlogName'), message);
} else if (WinJS.Utilities.hasClass(document.getElementById('shareQuote'), 'show')) {
WPCom.toggleElement(document.getElementById('publish-quote'), 'hide');
WinJS.Utilities.setInnerHTMLUnsafe(document.getElementById('quoteBlogName'), message);
}
document.querySelector('.signinout').addEventListener('click', WPCom.signInOut);
}
}
function followUnfollowBlog(m) {
var button = m.currentTarget;
var isFollowAction = false;
if (button.id == "follow-blog")
isFollowAction = true;
WPCom.toggleElement(document.getElementById("follow-blog"), 'hide');
WPCom.toggleElement(document.getElementById("unfollow-blog"), 'hide');
var progress = document.getElementById("publish-progress");
progress.style.display = "block";
WPCom.toggleElement(document.getElementById('shareLink'), 'hide');
document.getElementById("followStatusText").innerText = 'Processing your request';
var url = WPCom.apiURL + "/sites/" + document.getElementById("follow-blog-uri").value;
var okMessage = "";
if (isFollowAction) {
//follow blog
url = url + "/follows/new";
okMessage = "You're following " + document.getElementById("follow-blog-title").value;
} else {
//unfollow blog
url = url + "/follows/mine/delete";
okMessage = "You're not following " + document.getElementById("follow-blog-title").value;
}
var accessToken = WPCom.getCurrentAccessToken();
WinJS.xhr({
type: "POST",
url: url,
headers: { "Authorization": "Bearer " + accessToken },
}).then(function (result) {
progress.style.display = "none";
var resultData = JSON.parse(result.responseText);
if ( ( resultData.is_following == true && isFollowAction == true ) || ( resultData.is_following == false && isFollowAction == false ) ) {
document.getElementById("followStatusText").innerText = okMessage;
}
else {
//the desired action didn't work? ugh!
document.getElementById("errorMessage").innerText = "Sorry, something went wrong while processing your request. Please try again later.";
}
}, function (result) {
var resultData = JSON.parse(result.responseText);
document.getElementById("errorMessage").innerText = "Sorry, the following error occurred while processing your request: " + resultData.message;
progress.style.display = "none";
});
}