I'd like to upload a video and get direct URL to it (not a YouTube page, just a raw video file on a server). I've read here that youtube-dl can get such a direct link from YT video, but it returned something like this:
https://r5---sn-f5f7ln7s.googlevideo.com/videoplayback?id=5e338da1be872622&itag=
140&source=youtube&requiressl=yes&mm=31&pl=17&mn=sn-f5f7ln7s&mv=m&ms=au&ratebypa
ss=yes&mime=audio/mp4&gir=yes&clen=615762&lmt=1444814917264017&dur=38.730&key=dg
_yt0&signature=85FE55338A7ECBCA4895DFA3084A6C8CB7C09654.28AD612266C937BFBBD20135
D03031E824806B53&sver=3&mt=1444818958&fexp=9405191,9408210,9408710,9414764,94154
35,9415868,9416126,9417707,9418199,9418401,9418702,9420439,9420933,9421923,94220
62,9422545&upn=5cQZ5KNCvl0&ip=89.74.115.72&ipbits=0&expire=1444840721&sparams=ip
,ipbits,expire,id,itag,source,requiressl,mm,pl,mn,mv,ms,ratebypass,mime,gir,clen
,lmt,dur
The thing is, it plays but shows nothing (indeed, it opens as a video file). So it looks like YT is somehow protected from such actions.
Do you know any site that allows me to do such thing?
Thanks!
youtube-dl works to download videos from a wide variety of sites, not just YT
youtube-dl -c -l https://www.youtube.com/watch?v=fT88iVceBn4
Once you have a media file (audio/video) on your server (or your local machine), the following nodejs server will stream it to a URL ...
save below node code into file media_server.js then once you have nodejs installed launch the below code doing
node ./media_server.js
then point your browser at http://localhost:8888/
its a tiny media server which responds to all the standard media navigation widgets ... have fun
var http = require('http'),
fs = require('fs'),
util = require('util');
// var path = "/path/to/audio/or/video/file/local/to/server/cool.mp4"; // put any audio or video file here
var path = "/home/stens/Videos/kehoe/OliverSacks_2009-480p.mp4"; // put any audio or video file here
var port = 8888;
var host = "localhost";
http.createServer(function (req, res) {
var stat = fs.statSync(path);
var total = stat.size;
if (req.headers.range) { // meaning client (browser) has moved the forward/back slider
// which has sent this request back to this server logic ... cool
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' + end + '/' + total, 'Accept-Ranges': 'bytes', 'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, { 'Content-Length': total, 'Content-Type': 'video/mp4' });
fs.createReadStream(path).pipe(res);
}
}).listen(port, host);
console.log("Server running at http://" + host + ":" + port + "/");
Related
i am trying to upload image captured from camera using ionic and capacitor and below code i am using:
var url = 'https://api.cloudinary.com/v1_1/' + this.cloudName + '/image/upload';
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader("Access-Control-Allow-Origin","*")
xhr.onreadystatechange = (e) => {
this.loading = false;
if (xhr.readyState == 4 && xhr.status == 200) {
// File uploaded successfully
var response = JSON.parse(xhr.responseText);
var url = response.secure_url;
// Create a thumbnail of the uploaded image, with 150px width
var tokens = url.split('/');
tokens.splice(-2, 0, 'w_150,c_scale');
var img = new Image(); // HTML5 Constructor
img.src = tokens.join('/');
img.alt = response.public_id;
document.body.appendChild(img);
//window.alert(url);
this.imageUrl = url;
this.capturedImage = this.base64Image;
//alert('capture:' + capturedImage);
}else{
console.log("unable to load image to the cloud" + xhr.readyState + ":" + xhr.status + ":" + xhr.responseText)
}
};
fd.append('upload_preset', this.unsignedUploadPreset);
fd.append('tags', emailid); // Optional - add tag for image admin in Cloudinary
fd.append('file', this.base64Image);
xhr.send(fd);
it prints: unable to load image to the cloud 4:0:
I'm a little confused by your code because it looks like you are trying to access the response before you've actually sent anything. I would recommend using one of the Cloudinary SDKs as it will make your life a lot easier.
https://cloudinary.com/documentation/image_upload_api_reference#upload_examples
Here is an example of another upload using Ionic and Capacitor.
https://devdactic.com/ionic-image-upload-capacitor
As the title says I have some video saved on an s3 bucket. I set my nodejs to stream it on my react app. It works fine on all devices except iOS. I did some searches and I can't find the issue. The server is returning the initial bytes request as 206. I checked the headers but I can't find the issue:
Here is my nodejs:
After it reaches the path:
if (!range) {
res.status(400).send("returning err!");
return;
}
s3.headObject({
Bucket: process.env.AWS_BUCKET_NAME,
Key: req.params.key
}, function (err, data) {
if (err) {
// an error occurred
console.error(err);
return res.status(500).send("returning err");
}
const videoSize = Number(data.ContentLength);
const CHUNK_SIZE = 10 ** 6; // 1MB
const start = Number(range.replace(/\D/g, ""));
const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
var params = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: req.params.key,
Range: range,
};
var stream = s3.getObject(params).createReadStream();
res.status(206);
res.set('Content-Type', data.ContentType);
res.set('Content-Disposition','inline');
res.set('Accept-Ranges','bytes');
res.set('Accept-Encoding', 'Identity');
res.set('Content-Range', 'bytes ' + start + '-' + end + '/' + videoSize);
res.set('Content-Length', data.ContentLength);
res.set('X-Playback-Session-Id', req.header('X-Playback-Session-Id')); // Part of the attempt to fix
res.set('Connection', 'keep-alive');
res.set('Last-Modified', data.LastModified);
res.set('ETag', data.ETag);
stream.pipe(res);
Here is my Frontend React player code:
<ReactPlayer
ref={player}
// onProgress={onProgress}
playsinline={true}
url={[{ src: source, type: 'video/mp4;' }]} // video location
controls // gives the front end video controls
width='100%'
className='react-player'
height='100%'
allow='autoplay; encrypted-media'
allowFullScreen
// muted={true}
playing={playing}
onPlay={() => setPlaying(true)}
// onPause={() => setPlaying(false)} //part of the attempt to fix
// onSeek={(seek) => playerSeeker(seek)} //part of the attempt to fix
config={{
file: {
attributes: {
controlsList: 'nodownload'
}
}
}}
onContextMenu={e => e.preventDefault()}
onEnded={(e) => onVideoEnded(e)}
onError={(e) => onVideoError(e)}
/>
Again, the first request on iOS is returning a 206 success but node always ends the stream before it even start playing.
Turns out It was just the
res.set('Content-Length', data.ContentLength);
Instead of sending the full length for the video, I needed to return the length of the calculated range.
Here is the script for the button i am working on. the script creates the pdf and folder, Sends email but doesn't grab the attachment.
I have removed the file id and url ect.
The main section i am having problems is the attachment.
Really appreciate any help with this one.
function getpdf2(){
SpreadsheetApp.flush();
//make pdf
var theurl = ''
+ '' //the file ID
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=LETTER'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.50'
+ '&bottom_margin=0.50'
+ '&left_margin=0.50'
+ '&right_margin=0.50'
+ '&sheetnames=false&printtitle=false'
+ '&pagenum=false'
+ '&gridlines=false'
+ '&fzr=FALSE'
+ '&gid='
+ ''; //the sheet's Id
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token }
});
var fileid = DriveApp.createFile(docurl.getBlob()).setName('Quote mike.pdf').getId();
//var blob = spreadsheetFile.getAs('application/pdf');
var pdf = docurl.getBlob().setName('Quote mike.pdf');
var pdf = docurl.getBlob().getAs('application/pdf').setName('Quote mike.pdf');
var filetodel = DriveApp.getFileById(fileid);
DriveApp.getRootFolder().createFolder("mike"); //comment if folder exists
// if folder exists use next
if (DriveApp.getFoldersByName("mike").hasNext()){
var folder = DriveApp.getFoldersByName("mike").next();
filetodel.makeCopy(folder);
var address = Browser.inputBox('Enter Email Address', Browser.Buttons.OK_CANCEL);
//function sendEmailWithAttachments(){
//var fileid = SpreadsheetApp.getActiveSpreadsheet()
//getAs(MimeType.PDF);
MailApp.sendEmail({to:address,
subject: "QUOTE",
body:"Thank You!!",
attachments: [fileid[0].getAs(MimeType.pdf)]
})
DriveApp.removeFile(filetodel);
}
}
I am querying Neo4j database from node.js server and some queries sometimes run very slow and time out ultimately. I want to somehow get data in chunks in these particular cases and feed them gradually into the front end. I can't seem to find any good info on how to do that. Here is my node.js code:
router.get('/gene_expr', function(req, res) {
var geneName = req.query.geneName;
var datasetName = req.query.datasetName;
const expr_query =
'MATCH (c:Cell { DATASET: "' + datasetName + '"} )-[ex:EXPRESSES]->' +
'(g:Gene { geneName: "' + geneName + '" }) ' +
'WITH c, ex, g, round(avg(ex.expr)) AS AVG ' +
'WHERE ex.expr > AVG ' +
'RETURN c.tsneX, c.tsneY, ex.expr, c.cellId';
console.log(expr_query);
var driver = dbUtils.driver;
const session = driver.session();
session.run(
expr_query,
{}
).then(result => {
var exprData = chartService.prepareMarkerData(result, geneName);
res.json({
exprData
});
session.close();
});
})
I have never done such a thing. Would this npm package be good for the purpose: https://www.npmjs.com/package/cypher-stream ? If I use it, what else would I need to set up (headers, etc.) to allow for streaming data feed? On the front end I am using axios:
axios({
method:'get',
url:url,
responseType:'stream'
})
.then(function (response) { ... })
Any suggestions will be greatly appreciated.
I made an IOS 9 app using Phonegap 6.2.0. I need to play videos with no connection, so I download it using cordova FileTransfer plugin:
var uri = encodeURI(file.url);
var fileTransfer = new FileTransfer();
// var fileLocation = cordova.file.applicationStorageDirectory +
// '/Documents/' + file.folder + '/' + file.fileName;
var fileLocation = cordova.file.dataDirectory + file.fileName;
var deferred = $q.defer();
fileTransfer.headers = {
Connection: "close"
};
fileTransfer.download(uri, fileLocation, function(result) {
console.log("Fichero descargado: " + JSON.stringify(result));
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
I've tried different file locations to download it (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/)
Then, I return the file path using resolveLocalFileSystemURL:
var deferred = $q.defer();
var nativePath = cordova.file.dataDirectory + nombreFichero + "." + extension;
resolveLocalFileSystemURL(nativePath, function(entry) {
//deferred.resolve(entry.nativeURL);
console.log("Fichero native: " + entry.toNativeURL());
console.log("Fichero fullPath: " + entry.fullPath);
console.log("Fichero toUrl: " + entry.toURL());
console.log("Fichero toInternalURL: " + entry.toInternalURL());
deferred.resolve(entry.toURL());
}, function(error) {
console.log("Error al leer el fichero: " + JSON.stringify(error));
deferred.reject(error);
});
return deferred.promise;
I've tried all file formats but none of them worked:
cdvfile://localhost/library-nosync/97a7d50f-05d1-4642-96e9-b0b26ea41897.mp4
file:///var/mobile/Containers/Data/Application/6CD24D7A-7A39-4AFE-A43B-788FCDFCEB5A/Library/NoCloud/a88d38b8-85e8-4b9b-b57e-a8eb2731eb0d.mp4
http://localhost/library-nosync/97a7d50f-05d1-4642-96e9-b0b26ea41897.mp4 and using port 12344
Some formats do nothing, some show the button play strikethrough...
In all answers I had read they recommend to use .toNativeUrl() but it doesn't work for me...
I also tried cordova-plugin-streaming-media (I can't post more links), but it does not work (no play video, no errors...)
Any idea?
Solved.
My code works good and play videos. The problem was in the URL to download the video, it gets a string with the url and not the video (therefore download and open file method didin't throw error)
Summarizing, toUrl() works.
Thanks #Gandhi for your replies.