(function () {
"use strict";
var app = angular.module("items");
var templatePath =
modulesSharedResourcesUrl + "Modules/Items/Views/Directives/";
var manageTemplates = templatePath + "Manage/";
var previewTemplates = templatePath + "Preview/";
var showcaseTemplates = templatePath + "Showcases/";
var myprogressTemplates = templatePath + "MyProgress/";
// A directive that displays a form to manage a showcase item
app.directive("manageItemForm", function () {
return {
restrict: "E",
transclude: true,
templateUrl: showcaseTemplates + "manage-item-form.html",
};
});
// A directive that displays a form to manage a showcase add-in item
app.directive("manageAddinItemForm", function () {
return {
restrict: "E",
transclude: true,
templateUrl: showcaseTemplates + "manage-addin-item-form.html",
};
});
// A directive that shows a collage of items to add
app.directive("addItemCollage", function () {
return {
restrict: "E",
scope: {
createNewItem: "=",
selectedFolder: "=",
availableFolders: "=",
},
templateUrl: templatePath + "add-item-collage.html",
link: function (scope) {
scope.itemsToAdd = [
{
type: "status",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/text-note.png?version=270122",
title: "Create a text note",
body: "Create some text content, a blog post, some news or just some thoughts and reflections",
},
{
type: "image",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/image.png?version=270122",
title: "Upload an image",
body: "Upload an image file (JPG, GIF, PNG) directly into your Myshowcase account.",
},
{
type: "video",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/video.png?version=270122",
title: "Upload a video",
body: "Upload a video file directly into your Myshowcase account.",
},
{
type: "badge",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/openbadge.png?version=270122",
title: "Upload a badge",
body: "Upload a badge file (PNG) directly into your Myshowcase account.",
},
{
type: "badgecollection",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/badgecollection.png?version=270122",
title: "Add a badge collection",
body: "Add a badge collection as an item within your Myshowcase.me account",
},
{
type: "file",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/file.png?version=270122",
title: "Upload a file",
body: "Upload documents, presentations, spreadsheets, etc. directly into your Myshowcase account.",
},
{
type: "embed",
embedType: "embed-item",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/embed.png?version=270122",
title: "Add an embed item",
body: "Embed a link to a web site",
},
{
type: "embed",
embedType: "flickr",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/flickr.png?version=270122",
title: "Add a Flickr photo",
body: "Import any publicly shared photo from Flickr.",
},
{
type: "embed",
embedType: "slideshare",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/slideshare.png?version=270122",
title: "Add from SlideShare",
body: "Import a presentation shared on SlideShare.",
},
{
type: "embed",
embedType: "google-maps",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/map.png?version=270122",
title: "Add a Google Map",
body: "Import a map or satellite image using Google Maps.",
},
{
type: "embed",
embedType: "vimeo",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/vimeo.png?version=270122",
title: "Add a Vimeo video",
body: "Import any publicly shared video from Vimeo.",
},
{
type: "embed",
embedType: "youtube",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/youtube.png?version=270122",
title: "Add a Youtube video",
body: "Import any publicly shared video from YouTube.",
},
{
type: "embed",
embedType: "prezi",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/prezi.png?version=270122",
title: "Add from Prezi",
body: "Import a presentation created with Prezi.",
},
{
type: "embed",
embedType: "sketchfab",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/sketchfab.png?version=270122",
title: "Add a Sketchfab model",
body: "Import any publicly shared 3D model from Sketchfab.",
},
{
type: "embed",
embedType: "dailymotion",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/dailymotion.png?version=270122",
title: "Add a Dailymotion video",
body: "Import any publicly shared video from Dailymotion.",
},
{
type: "weblink",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/web-link.png?version=270122",
title: "Add a weblink",
body: "Add a link to a web site",
},
{
type: "zip",
thumbnail:
"https://uiframework.mkmapps.com/latest/lib/products/myshowcase/images/metro/zip-file.png?version=270122",
title: "Extract Zip File",
body: "Add a zip file and extract all content items",
},
];
},
};
});
// A directive to preview the content of an item before it is created
app.directive("itemPreview", [
"cloudinaryConfig",
function (config) {
return {
restrict: "E",
scope: {
item: "=",
fileData: "=",
previewUrl: "=",
},
templateUrl: previewTemplates + "item-preview.html",
link: function (scope) {
scope.cloudinaryVideoBaseUrl = config.videoBaseUrl;
},
};
},
]);
// A directive to view an item's content - such as an image or embed item
app.directive("itemViewer", [
"cloudinaryConfig",
function (config) {
return {
restrict: "E",
scope: {
item: "=",
onFormEdited: "&",
},
templateUrl: previewTemplates + "item-viewer.html",
link: function (scope) {
scope.cloudinaryVideoBaseUrl = config.videoBaseUrl;
},
};
},
]);
// A directive to edit an item's content and details
app.directive("itemDetailsEditor", function () {
return {
restrict: "E",
templateUrl: manageTemplates + "details-editor.html",
};
});
// A directive to edit an item's metadata (tags and frameworks)
app.directive("itemMetadataEditor", function () {
return {
restrict: "E",
templateUrl: manageTemplates + "metadata-editor.html",
};
});
// A directive to display folders available
app.directive("itemFolderEditor", function () {
return {
restrict: "E",
templateUrl: manageTemplates + "folder-editor.html",
};
});
// A directive to edit evidence / competencies for a framework
app.directive("itemFrameworksEditor", ["terminology", "$filter", function (terminology, $filter) {
return {
restrict: "E",
controller: "competencyTreeController",
templateUrl: manageTemplates + "frameworks-editor.html",
link: function (scope, _e, _a, ctrl) {
// Get all competencies for the selected framework
scope.setFramework = function (id) {
return ctrl.setFrameworkAndGetCompetencies(id).then(function (data) {
scope.retrievedAssignments[id] = data;
scope.uniqueSourceIds = [];
getDistinctSimpleEvidenceArray(data, scope.uniqueSourceIds);
ctrl.getTotalFileSize(scope.uniqueSourceIds).then(function (size) {
scope.totalSize = size;
});
});
};
// Check if an item has a competency
scope.itemHasEvidence = function (competency) {
var evidenceResult = competency.simpleEvidence.filter(function (v) {
return v.sourceId === scope.item.itemId && v.whatForDetailId === competency.id;
})[0];
return competency &&
(evidenceResult !== undefined ||
competency.addedAsEvidence);
};
// Check if an item has a locked evidence
scope.canNotMapReason = function (assignment, competency) {
if (assignment && competency.branches.length === 0) {
var size = scope.item.fileSize ? scope.item.fileSize : scope.item.imageFileSize ? scope.item.imageFileSize : scope.item.videoFileSize ? scope.item.videoFileSize : 0;
var evidenceResult = competency.simpleEvidence.filter(function (v) {
return v.sourceId === scope.item.itemId && v.whatForDetailId === competency.id;
})[0];
if (competency && evidenceResult !== undefined && evidenceResult.isLocked)
return terminology.progressEvidence.toUpperCaseFirstChar() + " is locked";
if (assignment.deploymentRules) {
if (evidenceResult === undefined && assignment.deploymentRules.restrictedItemTypes && assignment.deploymentRules.restrictedItemTypes.length > 0 && !assignment.deploymentRules.restrictedItemTypes.includes(scope.item.itemType)) {
return "This item type cannot be " + terminology.progressMapped + " on this " + terminology.progressViews;
}
if (evidenceResult === undefined && assignment.deploymentRules.maxEvidenceCount && competency.simpleEvidence.length >= assignment.deploymentRules.maxEvidenceCount) {
return "Max number of " + terminology.progressMapped + " " + terminology.progressEvidence + " on this " + terminology.competency;
}
if (evidenceResult === undefined && assignment.deploymentRules.maxTotalEvidenceCount && (scope.uniqueSourceIds.indexOf(scope.item.itemId) == -1 && scope.uniqueSourceIds.length >= assignment.deploymentRules.maxTotalEvidenceCount)) {
return "Max number of " + terminology.progressMapped + " " + terminology.progressEvidence + " on this " + terminology.progressViews;
}
if (evidenceResult === undefined && assignment.deploymentRules.maxTotalEvidenceSize && (size + scope.totalSize) > assignment.deploymentRules.maxTotalEvidenceSize) {
return "Size exceeds total " + $filter('filesize')(assignment.deploymentRules.maxTotalEvidenceSize);
}
if (evidenceResult === undefined && assignment.deploymentRules.maxEvidenceSize && size > assignment.deploymentRules.maxEvidenceSize) {
return "Size exceeds max " + $filter('filesize')(assignment.deploymentRules.maxEvidenceSize);
}
}
}
return null;
};
// Toggle evidence / a competency for an item
scope.toggleItemEvidence = function (competency) {
var evidenceResult = competency.simpleEvidence.filter(function (v) {
return v.sourceId === scope.item.itemId;
})[0];
if (evidenceResult) {
competency.addedAsEvidence = false;
competency.removedEvidence = competency.simpleEvidence.filter(function (v) {
return v.sourceId === scope.item.itemId;
});
competency.simpleEvidence = competency.simpleEvidence.filter(function (v) {
return v.sourceId !== scope.item.itemId;
})
scope.uniqueSourceIds = scope.uniqueSourceIds.filter(function (v) {
return v !== scope.item.itemId;
})
} else {
competency.addedAsEvidence = true;
scope.uniqueSourceIds.push(scope.item.itemId);
competency.simpleEvidence.push({
sourceId: scope.item.itemId,
whatForDetailId: competency.id
});
}
};
function getDistinctSimpleEvidenceArray(node, uniqueSourceIds) {
if (node.simpleEvidence) {
node.simpleEvidence.forEach((evidence) => {
if (evidence.sourceId && !uniqueSourceIds.includes(evidence.sourceId)) {
uniqueSourceIds.push(evidence.sourceId);
}
});
}
if (node.branches) {
node.branches.forEach((branch) => {
getDistinctSimpleEvidenceArray(branch, uniqueSourceIds);
});
}
}
},
};
},
]);
// A directive for embed items
app.directive("itemEmbedUpload", [
"validation",
function (validation) {
return {
restrict: "E",
scope: {
url: "=",
item: "=",
embedCode: "=",
},
templateUrl: manageTemplates + "item-embed-upload.html",
controller: "itemEmbedController",
link: function (scope) {
if (scope.item.embedType !== "embed-item")
scope.pattern = validation.getEmbedPattern(scope.item.embedType);
if (scope.item.embedType === "embed-item") scope.pattern = null;
scope.placeholder = validation.getEmbedPlaceholder(
scope.item.embedType
);
},
};
},
]);
// A directive for embedding a flickr image
app.directive("flickrEmbedUpload", [
function () {
return {
restrict: "E",
scope: {
url: "=",
},
templateUrl: manageTemplates + "flickr-embed-upload.html",
controller: "itemEmbedController",
link: function (scope) {
// Ensure that the url is in the correct format
scope.formatUrl = function (url) {
if (url) {
scope.ensureProtocol(url);
//lookup '/in/' and remove it and anything after it
if (url.indexOf("/in/") !== -1) {
var position = url.indexOf("/in/");
var replacedUrl = scope.url.substring(0, position);
scope.url = replacedUrl;
}
}
};
},
};
},
]);
// A directive for previewing an image item
app.directive("imageItemPreview", [
"cloudinaryConfig",
function (config) {
return {
restrict: "E",
scope: {
item: "=",
w: "@",
},
template:
'
![]()
',
link: function (scope) {
scope.baseImageUrl = config.baseUrl;
scope.w = scope.w || 600;
},
};
},
]);
// A directive for previewing a weblink item
app.directive("weblinkItemPreview", [
"cloudinaryConfig",
function (config) {
return {
restrict: "E",
scope: {
item: "=",
w: "@",
},
template:
'![]()
',
link: function (scope) {
scope.baseImageUrl = config.urlToPngBaseUrl;
scope.w = scope.w || 600;
},
};
},
]);
// A directive for previewing a badge item
app.directive("badgeItemPreview", [
"cloudinaryConfig",
function (config) {
return {
restrict: "E",
scope: {
item: "=",
w: "@",
},
templateUrl: previewTemplates + "preview-badge.html",
link: function (scope) {
scope.baseImageUrl = config.urlToPngBaseUrl;
scope.w = scope.w || 600;
},
};
},
]);
// A directive for previewing a badge collection item
app.directive("badgeCollectionItemPreview", [
"config",
function (config) {
return {
restrict: "E",
scope: {
item: "=",
},
template:
'',
link: function (scope) {
scope.collectionUrl =
config.siteUrl +
"view/#!/collection?collectionid=" +
scope.item.mybadgesCollectionId +
"&preview=true";
},
};
},
]);
// A directive for previewing a file item
app.directive("fileItemPreview", [
"userDataContext",
function (userDataContext) {
return {
restrict: "E",
scope: {
item: "=",
},
templateUrl: previewTemplates + "preview-file-item.html",
link: function (scope) {
// Get the users upload token
userDataContext.getUploadBucketSas().then(function (sas) {
scope.sasToken = sas.sas;
});
},
};
},
]);
// A directive for previewing an assessment item
app.directive("assessmentItemPreview", function () {
return {
restrict: "E",
templateUrl: previewTemplates + "preview-assessment-item.html",
};
});
// A directive for showing upload progress of an image item
app.directive("fileUploadProgress", function () {
return {
restrict: "E",
scope: {
uploadPercentage: "=",
},
templateUrl: manageTemplates + "file-upload-progress.html",
};
});
// A directive for managing an image item
app.directive("manageImageItem", [
"config",
function (config) {
return {
restrict: "E",
templateUrl: manageTemplates + "manage-image-item.html",
link: function (scope, element, _a, ngModel) {
scope.maxFileSize = config.maxImageUpload / 1e6;
},
};
},
]);
// A directive for managing a video item
app.directive("manageVideoItem", [
"config",
function (config) {
return {
restrict: "E",
templateUrl: manageTemplates + "manage-video-item.html",
link: function (scope, element, _a, ngModel) {
scope.maxFileSize = config.maxVideoUpload / 1e6;
},
};
},
]);
// A directive for managing a badge item
app.directive("manageBadgeItem", [
"config",
function (config) {
return {
restrict: "E",
templateUrl: manageTemplates + "manage-badge-item.html",
link: function (scope, element, _a, ngModel) {
scope.maxFileSize = config.maxFileUpload / 1e6;
},
};
},
]);
// A directive for managing a badge collection item
app.directive("manageBadgeCollectionItem", [
"config",
"datacontext",
function (config, datacontext) {
return {
restrict: "E",
transclude: true,
templateUrl: manageTemplates + "manage-badge-collection-item.html",
link: function (scope) {
// Badge collections data
scope.data = {
collections: [],
loaded: false,
};
// Get all available published and public collections
scope.collectionUrl =
config.siteUrl +
"view/#!/collection?collectionid=" +
scope.item.mybadgesCollectionId +
"&preview=true";
scope.noCollectionSelected = true;
scope.selectedCollection = scope.item.mybadgesCollectionId;
// todo: move this function out of datacontext (maybe to badges module?)
datacontext.getCollectionsForUser().then(function (data) {
scope.data.collections = data.reduce(function (
collections,
collection
) {
if (
collection.published &&
collection.publishedCollection.public
) {
collections.push(collection);
}
return collections;
},
[]);
scope.data.loaded = true;
});
// Set the preview url when badge collection is selected
scope.setCollectionPreview = function (collection) {
scope.noCollectionSelected = false;
scope.collectionUrl =
config.siteUrl +
"view/#!/collection?collectionid=" +
collection +
"&preview=true";
scope.item.mybadgesCollectionId = collection;
};
},
};
},
]);
// A directive for managing a weblink item
app.directive("manageWeblinkItem", function () {
return {
restrict: "E",
templateUrl: manageTemplates + "manage-weblink-item.html",
};
});
// A directive for managing a file item
app.directive("manageFileItem", [
"config",
function (config) {
return {
restrict: "E",
templateUrl: manageTemplates + "manage-file-item.html",
link: function (scope, element, _a, ngModel) {
scope.maxFileSize = config.maxFileUpload / 1e6;
},
};
},
]);
// A directive for managing a zip item
app.directive("manageZipItem", [
"config",
function (config) {
return {
restrict: "E",
templateUrl: manageTemplates + "manage-zip-item.html",
link: function (scope, element, _a, ngModel) {
scope.maxFileSize = config.maxFileUpload / 1e6;
},
};
},
]);
// MyProgress Assessment items
app.directive("showcaseItemAssessmentPreview", function () {
return {
restrict: "E",
templateUrl: myprogressTemplates + "assessment2.html",
scope: {
myShowcaseItem: "=item",
accessToken: "=",
},
link: function ($scope) {
$scope.templatePath = myprogressTemplates;
$scope.getLetter = function (index) {
if (0 <= index && index <= 25) {
return String.fromCharCode(65 + index);
} else if (26 <= index <= 51) {
return String.fromCharCode(71 + index);
} else {
return "";
}
};
$scope.getAssessmentItemResultFromCustomText = function (customText) {
var assessmentItemIdentifier =
$scope.getAssessmentItemIdentifier(customText);
if (assessmentItemIdentifier.length > 0) {
var result = $scope.getAssessmentItemResult(
assessmentItemIdentifier
);
return result;
}
return null;
};
$scope.getAssessmentItemResult = function (assessmentItemIdentifier) {
var resultArray =
$scope.myShowcaseItem.jsonResponse.Result.itemResults.filter(
function (assessmentItemResult) {
return (
assessmentItemResult.identifier === assessmentItemIdentifier
);
}
);
if (resultArray.length > 0) {
return resultArray[0];
} else {
return null;
}
};
$scope.getAssessmentItemIdentifier = function (customText) {
var identifierString = "identifier:";
if (
customText &&
customText.length > 0 &&
customText.indexOf(identifierString) > -1
) {
var startIndex =
customText.indexOf(identifierString) + identifierString.length;
return customText.substring(startIndex);
}
return "";
};
$scope.isAssessmentItemHidden = function (customText) {
if (customText && customText.length > 0) {
for (
var i = 0;
i <
$scope.myShowcaseItem.jsonResponse.HiddenAssessmentItemIdentifiers
.length;
i++
) {
if (
customText.includes(
$scope.myShowcaseItem.jsonResponse
.HiddenAssessmentItemIdentifiers[i]
)
) {
return true;
}
}
}
return false;
};
},
};
});
app.directive("myprogressAssessmentItemPreview", function () {
return {
restrict: "E",
templateUrl: myprogressTemplates + "assessmentResponseItem.html",
scope: {
myShowcaseItem: "=",
assessmentItem: "=",
itemResult: "=",
accessToken: "=",
},
link: function ($scope) {
$scope.getSelectedInteractionOptions = function (
assessmentItemResult,
responseIdentifier
) {
if (assessmentItemResult && responseIdentifier) {
var responseValues = assessmentItemResult.responseValues.filter(
function (responseValue) {
return responseValue.identifier === responseIdentifier;
}
);
if (responseValues.length > 0) {
return responseValues[0].values;
} else {
return null;
}
} else {
return null;
}
};
$scope.getSingleResponseValue = function (
assessmentItemResult,
responseIdentifier
) {
if (assessmentItemResult && responseIdentifier) {
var responseValues = assessmentItemResult.responseValues.filter(
function (responseValue) {
return responseValue.identifier === responseIdentifier;
}
);
if (responseValues && responseValues.length > 0) {
var responseValueArray = responseValues[0].values;
if (responseValueArray && responseValueArray.length > 0) {
return responseValueArray[0];
} else {
return null;
}
} else {
return null;
}
} else {
return null;
}
};
$scope.isInCorrectValues = function (
responseValue,
correctValues,
correctValue,
correctDate,
correctTime,
dateFormat
) {
return (
(responseValue &&
responseValue.length &&
correctValues &&
correctValues.length > 0 &&
correctValues.includes(responseValue)) ||
(correctValue &&
correctValue.length > 0 &&
correctValue == responseValue) ||
(correctDate &&
correctDate.length > 0 &&
$scope.compareDateStrings(
correctDate,
responseValue,
dateFormat
)) ||
(correctTime &&
correctTime.length > 0 &&
$scope.compareTimeStrings(correctTime, responseValue))
);
};
$scope.compareTimeStrings = function (time1, time2) {
if (time1 && time2) {
var t1 = time1.split(":");
var t2 = time2.split(":");
var h1 = parseInt(t1[0]);
var h2 = parseInt(t2[0]);
var m1 = parseInt(t1[1]);
var m2 = parseInt(t2[1]);
return h1 == h2 && m1 == m2;
} else {
return false;
}
};
$scope.compareDateStrings = function (
correctDate,
responseDate,
dateFormat
) {
var dateCorrect = new Date(correctDate);
var dayCorrect = dateCorrect.getDate();
var monthCorrect = (dateCorrect.getMonth() + 1).toString();
if (monthCorrect.length == 1) {
monthCorrect = "0" + monthCorrect;
}
var yearCorrect = dateCorrect.getFullYear().toString();
var stringCorrect = "";
if (dateFormat == "DATE") {
stringCorrect = dayCorrect + "/" + monthCorrect + "/" + yearCorrect;
} else {
var hoursCorrect = dateCorrect.getHours().toString();
var minutesCorrect = dateCorrect.getMinutes().toString();
if (hoursCorrect.length == 1) {
hoursCorrect = "0" + hoursCorrect;
}
if (minutesCorrect.length == "1") {
minutesCorrect = "0" + minutesCorrect;
}
stringCorrect =
dayCorrect +
"/" +
monthCorrect +
"/" +
yearCorrect +
" " +
hoursCorrect +
":" +
minutesCorrect;
}
return stringCorrect == responseDate;
};
},
};
});
app.directive("myprogressInteractionChoicePreview", function () {
return {
restrict: "E",
templateUrl: myprogressTemplates + "assessmentResponseChoice.html",
scope: {
simpleChoice: "=",
selectedValues: "=",
correctValues: "=",
},
link: function ($scope) {
$scope.isSelected = function () {
return (
$scope.selectedValues &&
$scope.selectedValues.length > 0 &&
$scope.selectedValues.includes($scope.simpleChoice.Identifier)
);
};
$scope.isCorrect = function () {
return (
$scope.correctValues &&
$scope.correctValues.length > 0 &&
$scope.correctValues.includes($scope.simpleChoice.Identifier)
);
};
$scope.isIncorrect = function () {
//value is incorrect only if there are defined correct values
return (
$scope.correctValues &&
$scope.correctValues.length > 0 &&
!$scope.correctValues.includes($scope.simpleChoice.Identifier)
);
};
},
};
});
app.directive("myProgressInteractionGridPreview", function () {
return {
restrict: "E",
templateUrl: myprogressTemplates + "assessmentResponseGrid.html",
scope: {
sourceItems: "=",
targetItems: "=",
selectedValues: "=",
},
link: function ($scope) {
$scope.isSelected = function (sourceId, targetId) {
return (
$scope.selectedValues &&
$scope.selectedValues.length > 0 &&
$scope.selectedValues.includes(sourceId + " " + targetId)
);
};
},
};
});
app.directive("myProgressInteractionFilePreview", [
"$http",
"$timeout",
"$window",
function ($http, $timeout, $window) {
return {
restrict: "E",
templateUrl: myprogressTemplates + "assessmentResponseFile.html",
scope: {
myShowcaseItemId: "=",
streamedResourceData: "=",
responseString: "=",
accessToken: "=",
},
link: function ($scope) {
function fileNameFromResponse() {
if (
$scope.responseString &&
$scope.responseString.indexOf(",") > 0
) {
return $scope.responseString.substring(
$scope.responseString.indexOf(",") + 1
);
} else {
return "";
}
}
function fileGuidFromResponse() {
if (
$scope.responseString &&
$scope.responseString.indexOf(",") > 0
) {
return $scope.responseString.substring(
0,
$scope.responseString.indexOf(",")
);
} else {
return "";
}
}
$scope.fileName = fileNameFromResponse();
$scope.fileGuid = fileGuidFromResponse();
//&userid=9F33C4E1-7A70-47B4-9C1C-A46A40B67D8D
function fileDownloadUrl() {
if (
$scope.fileGuid &&
$scope.fileGuid.length > 0 &&
$scope.fileName &&
$scope.fileName.length > 0
) {
return (
"/api/myitem/" +
$scope.myShowcaseItemId +
"/zipcontents?name=" +
$scope.fileGuid +
"&originalName=" +
$scope.fileName
);
}
return "";
}
function resourceIsImage() {
if ($scope.streamedResourceData) {
var isImage = false;
for (var i = 0; i < $scope.streamedResourceData.length; i++) {
if (
$scope.streamedResourceData[i].ResourceId == $scope.fileGuid
) {
isImage =
$scope.streamedResourceData[i].Type.toLowerCase().indexOf(
"image"
) >= 0;
break;
}
}
return isImage;
}
}
function getResourceType() {
if ($scope.streamedResourceData) {
var rType = "";
for (var i = 0; i < $scope.streamedResourceData.length; i++) {
if (
$scope.streamedResourceData[i].ResourceId == $scope.fileGuid
) {
rType = $scope.streamedResourceData[i].Type;
break;
}
}
return rType;
}
}
$scope.fileUrl = fileDownloadUrl();
$scope.isImage = resourceIsImage();
$scope.resourceType = getResourceType();
function getResourceAsBase64Url() {
var maxSizeForBase64 = 3000050; //4Gb max data url for IE - 50 bytes for metadata
var url = $scope.fileUrl;
var request = $http({
method: "get",
url: url,
headers: {
Authorization: "Bearer " + $scope.accessToken,
},
responseType: "arraybuffer",
});
return request.then(function (response) {
var arrayBuffer = response.data;
if (arrayBuffer) {
var u8 = new Uint8Array(arrayBuffer);
if (u8.length <= maxSizeForBase64) {
var len = u8.byteLength;
var binary = "";
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(u8[i]);
}
var b64encoded = window.btoa(binary);
var mimetype = $scope.resourceType;
return "data:" + mimetype + ";base64," + b64encoded;
} else {
return "";
}
} else {
return "";
}
}, $scope.handleError);
}
$scope.handleError = function (response) {
console.log(response);
};
$scope.handleSuccess = function (response) {
return response.data;
};
function downloadFileUrl() {
//var maxSizeForBase64 = 1048576; //1024 * 1024
//use dataurl if it exists - only get data again if base64Url hasn't been generated
//if (!$scope.base64Url || $scope.base64Url.length == 0) {
var request = $http({
method: "get",
url: $scope.fileUrl,
headers: {
Authorization: "Bearer " + $scope.accessToken,
},
responseType: "arraybuffer",
});
return request.then(function (response) {
var str = response.data;
var windowUrl = window.URL || window.webkitURL;
if (typeof windowUrl.createObjectURL === "function") {
var blob = new Blob([str], { type: $scope.resourceType });
var url = windowUrl.createObjectURL(blob);
return url;
} else {
return "";
}
}, $scope.handleError);
//}
//else {
// return new Promise(function(resolve, reject) {
// return resolve($scope.base64Url);
// //return reject('error');
// })
//}
}
//getResourceAsBase64Url().then(function (response) {
// $scope.base64Url = response;
// downloadFileUrl().then(function (response) {
// $scope.downloadFileLocation = response;
// })
//})
downloadFileUrl().then(function (response) {
$scope.downloadFileLocation = response;
});
$scope.useIEDownload = window.navigator.msSaveOrOpenBlob;
$scope.doIEDownload = function () {
var request = $http({
method: "get",
url: $scope.fileUrl,
headers: {
Authorization: "Bearer " + $scope.accessToken,
},
responseType: "arraybuffer",
});
return request.then(function (response) {
var str = response.data;
var windowUrl = window.URL || window.webkitURL;
if (typeof windowUrl.createObjectURL === "function") {
var blob = new Blob([str], { type: $scope.resourceType });
window.navigator.msSaveOrOpenBlob(blob, $scope.fileName);
} else {
return "";
}
}, $scope.handleError);
};
},
};
},
]);
})();