Need help to implement PhoneGap/Cordova ContentSync Plugin - http

Have a question regarding contentsync phonegap plugin (https://www.npmjs.com/package/phonegap-plugin-contentsync).
Will be very appreciated if someone could help.
The core of the problem is that my REST server allowing me to download .epub files (witch are same as .zip) only by sending GET request similar to:
https://test-api.books.com/api/getPublishedEpub?session_hash=1235&publication_id=abv1243'
Providing this link to the plugin '.sync' call I get a 'Invalid request method' response from the server...
While trying to download ordinary .zip everything works just fine.
var pub_id = $scope.currentBook.publication_id, epubUrl = 'https://test-api.books.com/api/getEpub?session_hash='
+ $rootScope.sessionHash+ '&publication_id=' + pub_id;
var downloadBtn = document.getElementById("downloadBtn");
console.log('Download cliked');
var sync = ContentSync.sync({ src: epubUrl, id: 'book'+ pub_id});
sync.on('progress', function (data) {
downloadBtn.innerHTML = "Downloading: " + data.progress + "%";
});
sync.on('complete', function (data) {
console.log(data.localPath);
for (var x = 1; x <= 17; x++) {
var fileUrl = "file://" + data.localPath;
console.log(fileUrl);
}
downloadBtn.innerHTML = 'Download';
});

Related

Check InDesign Links for missing XMP - DocumentID and InstanceID

I am using ExtendScript to work on metadata information of .indd files in InDesignCC 2019.
My requirement is that I need to access all individual links metadata associated with the .indd file and see whether any of the links metadata is missing DocumentID and InstanceID. If any of the links metadata do not have a value for DocumentID and/or InstanceID properties then I need to display the file name associated with that link, indicating that, that particular file is missing a DocumentID and/or InstanceID.
I have used the below script to access the meta data of .indd file.
$.level=0
// load XMP Library
function loadXMPLibrary() {
if (!ExternalObject.AdobeXMPScript) {
try{ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');}
catch (e){alert('Unable to load the AdobeXMPScript library!'); return false;}
}
return true;
}
var myFile= app.activeDocument.fullName;
var myXmp = null;
// check library and file
if (loadXMPLibrary() && myFile !== null) {
xmpFile = new XMPFile(myFile.fsName, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_UPDATE);
myXmp = xmpFile.getXMP();
$.writeln(xmpFile.getPacketInfo());
}
if (myXmp){
$.writeln (myXmp);
$.writeln (XMPFile.getFormatInfo(XMPConst.FILE_INDESIGN));
}
Can any one help me how can I proceed further in this?
Once you've obtained the XMP from the link, i.e. xmpFile.getXMP(), you'll need to:
Utilize the getProperty() method to retrieve the value of a specific metadata property.
Typically the DocumentID and InstanceID will be associated with the NS_XMP_MM schema namespace, which is described as:
NS_XMP_MM The XML namespace for the XMP digital asset management schema.
For instance, to obtain the DocumentID you'll do something like the following:
var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
Solution:
The gist below (example.jsx) performs the following:
Checks whether a .indd file is open and notifies the user if there is not one open.
Loads the AdobeXMPScript XMP Library
Checks that the status of all Links are "OK", i.e. it checks that they are not "Modified", nor "Missing". If any link status is not "OK" the user is asked to update their status to "OK".
Checks whether each linked asset has a DocumentID and InstanceID and logs their values to the JavaScript Console.
For any linked asset that does not have a DocumentID and/or InstanceID an alert dialog appears indicating the name and path to the linked asset.
example.jsx
$.level=0;
// Warn if there are no documents open.
if (!app.documents.length) {
alert('Open a document and try again.', 'Missing Document', false);
exit();
}
var doc = app.activeDocument;
// load XMP Library
function loadXMPLibrary() {
if (!ExternalObject.AdobeXMPScript) {
try {
ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
} catch (e) {
alert('Failed loading AdobeXMPScript library\n' + e.message, 'Error', true);
return false;
}
}
return true;
}
// Check all link statuses are be ok.
function linksStatusCheck(doc) {
for (var i = 0, len = doc.links.length; i < len; i++) {
if (doc.links[i].status !== LinkStatus.NORMAL) {
alert('The status of all links must be OK \nPlease update link status ' +
'via the Links panel and try again', 'Link Status', true);
exit();
}
}
return true;
}
function checkLinksXMP(doc) {
for (var i = 0, len = doc.links.length; i < len; i++) {
var linkFilepath = File(doc.links[i].filePath).fsName;
var linkFileName = doc.links[i].name;
var xmpFile = new XMPFile(linkFilepath, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_READ);
var allXMP = xmpFile.getXMP();
// Retrieve values from external links XMP.
var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
var instanceID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);
// Useful for testing purposes....
// Log properties for each link to the console.
$.writeln('linkName: ' + linkFileName);
$.writeln('filePath: ' + linkFilepath);
$.writeln('DocumentID: ' + documentID);
$.writeln('InstanceID: ' + instanceID);
$.writeln('-------------------------------------');
// Notify user when XMP is missing...
if (!documentID && !instanceID) {
alert('Link missing DocumentID and InstanceID\n' +
'Name: ' + linkFileName + '\n\n' +
'Path: ' + linkFilepath, 'Missing XMP', true);
} else if (!documentID) {
alert('Link missing DocumentID\n' +
'Name: ' + linkFileName + '\n\n' +
'Path: ' + linkFilepath, 'Missing XMP', true);
} else if (!instanceID) {
alert('Link missing InstanceID\n' +
'Name: ' + linkFileName + '\n\n' +
'Path: ' + linkFilepath, 'Missing XMP', true);
}
}
}
if (loadXMPLibrary() && linksStatusCheck(doc)) {
checkLinksXMP(doc);
}

showing video using react-native-video, from express using GridFSBucket

I have a difficulty here showing video using react-native-video.
The server is using Express, and using GridFSBucket to retrieve the video from mongodb.
The problem is that:
The video from GridFSBucket won't show. But when I tried to place the video in public folder, it will show.
So, my guess is that there is something wrong with how I serve the video. Here is my code from the server:
const bucket = new GridFSBucket(db.original(), { bucketName: "fs" });
const fileDetail = await db.original().collection("fs.files").findOne({_id: idObj});
if (isNullOrUndefined(fileDetail)) {
throw new NoContentException(`asset not found for id ${id}`);
}
const range = req.headers["range"]
if (range && typeof range === "string") {
const parts = range.replace(/bytes=/, "").split("-");
const partialstart = parts[0];
const partialend = parts[1];
const start = parseInt(partialstart, 10);
const end = partialend ? parseInt(partialend, 10) : fileDetail.length - 1;
const chunksize = (end - start) + 1;
res.writeHead(206, {
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Range': 'bytes ' + start + '-' + end + '/' + fileDetail.length,
'Content-Type': fileDetail.contentType
});
bucket.openDownloadStream(idObj, {start, end}).pipe(res);
} else {
res.header('Content-Length', fileDetail.length);
res.header('Content-Type', fileDetail.contentType);
bucket.openDownloadStream(idObj).pipe(res);
}
Thanks in advance for your answer ^_^
I found the solution.
The line:
bucket.openDownloadStream(idObj, {start, end}).pipe(res);
should be:
bucket.openDownloadStream(idObj, {start, end: end - 1}).pipe(res);

No data has been sent through CasperJS ajax

I am working on Casper JS web scraping, for now I have scraped the title from a site. I am making ajax request to the php file where I am collecting the data through post, but the data is not being sent through it while the response status is 200 and OK I don't know what is causing the problem.
The rest of the data is inserted successfully into the table, but not the title.
var casper = require('casper').create();
casper.start("https://www.google.com/");
casper.then(function(){
var data = this.evaluate(function(){
var title = document.getElementsByTagName('title')[0].textContent;
return title;
})
console.log(data);
casper.thenOpen("http://localhost/fiverr/Crawl%20The%20Jobs/modal_scripts.php",{method:"POST",data:data+"&crawled_jobs=true"}).then(function(res){
console.log(res.status);
})
})
casper.run();
The PHP script, I am collecting data in :
if (isset($_POST["crawled_jobs"])) {
$title = $_POST["data"];
$jobs_list_insert = "INSERT INTO jobs VALUES(null,'$title','nady','ahmad','kahn','yess','yesss')";
$con->query($jobs_list_insert);
}
Found a solution :
var i = 0;
console.log("Data Length : " + d.length);
function sendData(i) {
console.log("Posting Data...");
casper.thenOpen("http://localhost/fiverr/Crawl%20The%20Jobs/modal_scripts.php", {
method: "POST",
data: "title=" + d[i].title + "&loc=" + d[i].loc + "&day=" + d[i].day + "&salary=" + d[i].salary + "&link=" + d[i].link + "&logo=" + d[i].compLogo + "&crawled_jobs=true",
async: false
}).then(function(res) {
console.log(res.status);
sendData(i + 1);
})
}
sendData(i);

How To Modifying The Filename Before Uploading When Using Meteor Edgee:SlingShot Package

Please i am trying to modify the filename of a selected file posted by a user before uploading to Amazon S3 using the edgee:slinghot package. I can upload the file quite alright but the problem is how do i modify the filename.
I modified it on the client using by saving the modified name into a variable. My problem now is how to access that variable declared and saved on the Client in the Server environment. I just can't seem to wrap my head around it.
'change .js-submitTeamPaper' : function(event , template){
event.preventDefault();
let paper = template.paperDetails.get();
newFilename = paper[0].paper_name + "_"
_.map(paper[0].member , (member)=>{
newFilename += "_" + member.regnum + "_"
});
newFilename += paper[0]._id;
let file = event.target.value;
let fileArray = file.split(".");
let ext = fileArray[fileArray.length - 1];
newFilename += "." + ext;
studentFileUpload(event , template , 'submitTeamTermPaper' , 'divProgress');
}
The code to upload the file.
let _collectfile = (event , template) =>{
let file = event.target.files[0]
return file
}
let _showProgressBar = (div) => {
let _div = document.getElementById(div);
_div.classList.remove("hide");
}
let _closeProgressBar = (div) => {
let _div = document.getElementById(div);
_div.classList.add("hide");
}
let _slingShotUploadConfigure = (event , template , folder ,div) => {
let _upload = new Slingshot.Upload(folder);
let _file = _collectfile(event , template);
_showProgressBar(div);
_upload.send(_file , (error , downloadUrl) => {
template.uploader.set();
if (error){
//throw new Meteor.Error('500' , error.reason);
event.target.value = '';
sAlert.error(error.reason , {effect: 'bouncyflip',
position: 'bottom-right', timeout: 3000, onRouteClose: false, stack: false, offset: '150px'});
_closeProgressBar(div);
}
else{
sAlert.success('File was uploaded successfully' , {effect: 'genie',
position: 'bottom-right', timeout: 3000, onRouteClose: false, stack: false, offset: '150px'});
event.target.value = '';
template.downloadUrl.set(downloadUrl);
_closeProgressBar(div);
//return downloadUrl;
}
});
template.uploader.set(_upload);
}
export default function(event , template , folder ,div , progress){
return _slingShotUploadConfigure(event , template , folder,div , progress)
}
I then imported the module as studentFileUpload from '../../modules/handle-fileuploads';
Below is the meteor-slingshot code to do the upload
Slingshot.createDirective("submitTeamTermPaper", Slingshot.S3Storage, {
bucket: Meteor.settings.BucketName,
AWSAccessKeyId : Meteor.settings.AWSAccessKeyId,
AWSSecretAccessKey : Meteor.settings.AWSSecretAccessKey,
acl: "public-read",
authorize: function () {
// do some validation
// e.g. deny uploads if user is not logged in.
if (this.userId) {
return true;
}
},
key: function (file) {
//file here is the file to be uploaded how do i get the modified file name i defined in the client as newFilename here
let timeStamp = + new Date;
//let newFilename = file.name.replace(/_/g , "-");
return 'Team_Term_Papers/' + timeStamp + '_' + '_' + newFilename;
}
});
From my code newFilename is the variable that holds the modified filename. How do i access it from the server environment. Any help is really appreciated. Thanks
You can pass extra information through to slingshot using metacontext:
metacontext = {newName: "foo"};
let _upload = new Slingshot.Upload(folder,metacontext);
Then you can access that metacontext in your key function:
key: function (file,metacontext) {
let timeStamp = + new Date;
let newFilename = metacontext ? metacontext.newName : file.name;
newFilename = newFilename.replace(/_/g , "-");
return 'Team_Term_Papers/' + timeStamp + '_' + '_' + newFilename;
}

Uploading to Azure

I'm having an issue trying to directly upload a file to azure blob storage. I am using ajax calls to send post requests to an ashx handler to upload a blob in chunks. The issue I am running into is the handler isn't receiving the filechunk being sent from the ajax post.
I can see the page is receiving the post correctly from looking at the request in firebug,
-----------------------------265001916915724 Content-Disposition: form-data; >name="Slice"; filename="blob" Content-Type: application/octet-stream
I noticed the input stream on the handler has the filechunk, including additional bytes from the request. I tryed to read only the filechunk's size from the inputstream, however this resulted in an corrupt file.
I got the inspiration from http://code.msdn.microsoft.com/windowsazure/Silverlight-Azure-Blob-3b773e26 , I simply converted it from MVC3 to using standard aspx.
Here is the call using ajax to send the file chunk to the aspx page,
var sendFile = function (blockLength) {
var start = 0,
end = Math.min(blockLength, uploader.file.size),
incrimentalIdentifier = 1,
retryCount = 0,
sendNextChunk, fileChunk;
uploader.displayStatusMessage();
sendNextChunk = function () {
fileChunk = new FormData();
uploader.renderProgress(incrimentalIdentifier);
if (uploader.file.slice) {
fileChunk.append('Slice', uploader.file.slice(start, end));
}
else if (uploader.file.webkitSlice) {
fileChunk.append('Slice', uploader.file.webkitSlice(start, end));
}
else if (uploader.file.mozSlice) {
fileChunk.append('Slice', uploader.file.mozSlice(start, end));
}
else {
uploader.displayLabel(operationType.UNSUPPORTED_BROWSER);
return;
}
var testcode = 'http://localhost:56307/handler1.ashx?create=0&blockid=' + incrimentalIdentifier + '&filename=' + uploader.file.name + '&totalBlocks=' + uploader.totalBlocks;
jqxhr = $.ajax({
async: true,
url: testcode,
data: fileChunk,
contentType: false,
processData:false,
dataType: 'text json',
type: 'POST',
error: function (request, error) {
if (error !== 'abort' && retryCount < maxRetries) {
++retryCount;
setTimeout(sendNextChunk, retryAfterSeconds * 1000);
}
if (error === 'abort') {
uploader.displayLabel(operationType.CANCELLED);
uploader.resetControls();
uploader = null;
}
else {
if (retryCount === maxRetries) {
uploader.uploadError(request.responseText);
uploader.resetControls();
uploader = null;
}
else {
uploader.displayLabel(operationType.RESUME_UPLOAD);
}
}
return;
},
success: function (notice) {
if (notice.error || notice.isLastBlock) {
uploader.renderProgress(uploader.totalBlocks + 1);
uploader.displayStatusMessage(notice.message);
uploader.resetControls();
uploader = null;
return;
}
++incrimentalIdentifier;
start = (incrimentalIdentifier - 1) * blockLength;
end = Math.min(incrimentalIdentifier * blockLength, uploader.file.size);
retryCount = 0;
sendNextChunk();
}
});
};
Thanks so much for anything that can help me out.
is it ASPX on purpose? in http://localhost:56307/handler1.ashx?create=0&blockid?
Turns out on my webform, the input file tag was missing the enctype="multipart/form-data" attribute.

Resources