I'm streaming small videos from django view:
def play(request):
filename = settings.VIDEO_URL + extra_path
wrapper = FileWrapper(file(filename, "rb"))
response = HttpResponse(wrapper)
response['Content-Type'] = 'video/mp4'
response['Content-Length'] = os.path.getsize(filename)
return response
And have html code like this:
<video style="display: inline-block; width:500px; height:700px;">
<source type="video/mp4" src="play?v=1111">
<video>
Everything works fine, but i need to get video screenshot from JS for drawing above the video frame in canvas. I'm using it:
var video = document.querySelector('video');
var canvas = document.getElementById('canvas-bg');
var context = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
context.fillRect(0, 0, w, h);
context.drawImage(video, 0, 0, w, h);
It works good in Chrome, but i always getting empty context in Safari after context.drawImage(...).
Before django i used php script, like in this link: Streaming an mp4 through a php file progressively, and safari well worked.
Also if i'm changing:
<source type="video/mp4" src="play?v=1111">
to:
<source type="video/mp4" src="/static/video/myfunnyvideo.mp4">
I can get video context in safari! Why? Can anyone help me please.
Don't know why it happens, maybe some http headers are wrong, but I've found other solution for nginx server (for Apache you can use XSendFile):
def play(request):
extra_path = "myfunnyvideo.mp4"
filename = settings.VIDEO_URL + extra_path
response = HttpResponse(mimetype='video/mp4')
response['Accept-Ranges'] = 'bytes'
response['X-Accel-Redirect'] = filename
return response
and in nginx config (/etc/nginx/sites-available/your-site):
location /videos/ {
internal;
alias /var/www/some-folder/protected-folder;
}
Related
I published my django site but everyday i am finding new problems :)
Today i realised my images in the article has no slugify link.
Forexample in this page https://www.endustri.io/monokristal-gunes-paneli-nedir-calisma-prensibi-avantajlari/
my tinymce settings is
{
"height": 500,
"entity_encoding": "raw",
"menubar": "file edit view insert format tools table help",
"plugins": 'print preview paste importcss searchreplace autolink autosave save code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons quickbars',
"toolbar": "fullscreen preview | undo redo | bold italic forecolor backcolor | formatselect | image link | "
"alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | fontsizeselect "
"emoticons | ",
"custom_undo_redo_levels": 50,
"quickbars_insert_toolbar": False,
"file_picker_callback": """function (cb, value, meta) {
var input = document.createElement("input");
input.setAttribute("type", "file");
if (meta.filetype == "image") {
input.setAttribute("accept", "image/*");
}
if (meta.filetype == "media") {
input.setAttribute("accept", "video/*");
}
input.onchange = function () {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
var id = "blobid" + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(",")[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name });
};
reader.readAsDataURL(file);
};
input.click();
}""",
"content_style": "body { font-family:Roboto,Helvetica,Arial,sans-serif; font-size:14px }",
}
And i found these codes
'images_upload_handler': 'function(blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open("POST", "/path/to/upload/handler");
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure("HTTP Error: " + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != "string") {
failure("Invalid JSON: " + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append("file", blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}',
I added these codes to my actual codes but i recieve an error like this.
This image has url like this.
How can i make this image url like endustri.io/(image or media)/image-name.webp
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAApQAAAGVCAMAAAB3pZE2AAAC2VBMVEXz8/Tz8/QoKCktLS4iQX0iRYI6OjwgNmz///8xMTMhQ38hSIchSoo2NjdYWFohPnchOnIhQn5/f4EhR4W+H3DMzM6mpqchRYQhSIYiRoPI0eEhRIJeXl9iYmTX19fIz97p6eoAAACbnaBuRO/Wi/Sf2N27f+CaPUOkapdYxS6xil1jFKrWOUWscotY5Rah2j1DpGqXWMUusYpdb5AlujV99XpgrKAAAAAElFTkSuQmCC
You receive these errors because the value of the property 'images_upload_handler' (Line 187) is a JavaScript function that extends over several lines. This JavaScript function is a multi line string, like the JavaString function in Line 161 for the property 'file_picker_callback'. You have to treat the JavaScript function in Line 187 the same way. Write in Line 187
'images_upload_handler': """function( ...
and at the end of the JavaScript functino in Line 208
}""",
For further Details on multiline strings in Python see https://stackoverflow.com/a/10660443/5655611
Per default, TinyMCE stores images as data URL. This URL contains the data of the whole image. That's why the URL is so long. With data URLs it is possible to embed images directly into HTML. So you can save text, formatting and images i.e. all data of a single document in a single HTML file. That also has advantages.
To save the images separately:
Use images_upload_url instead of images_upload_handler. That is easier.
If you configure an images_upload_url, a file upload function is already integrated in Tiny Mce. I.e. you don't need file_picker_callback.
That means you can use the following for your Tiny Mce settings
{
"height": 500,
"entity_encoding": "raw",
"menubar": "file edit view insert format tools table help",
"plugins": 'print preview paste importcss searchreplace autolink autosave save code visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount imagetools textpattern noneditable help charmap emoticons quickbars',
"toolbar": "fullscreen preview | undo redo | bold italic forecolor backcolor | formatselect | image link | "
"alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | fontsizeselect "
"emoticons | ",
"custom_undo_redo_levels": 50,
"quickbars_insert_toolbar": False,
"content_style": "body { font-family:Roboto,Helvetica,Arial,sans-serif; font-size:14px }",
"images_upload_url": "upload-file",
}
In order for the url upload-file to work, you have to make following adjustments:
Settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Urls.py:
urlpatterns = [
...
path("upload-file", views.upload_file, name="upload_file"),
...
]
Views.py:
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from slugify import slugify
import os
import json
import urllib.parse
#csrf_exempt
def upload_file(request):
file= request.FILES['file']
filename= file.name
filenameParts= os.path.splitext(file.name)
slugifiedFilename= slugify(filenameParts[0]) + filenameParts[1]
osFilename= os.path.join(settings.MEDIA_ROOT, slugifiedFilename)
with open(osFilename, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
url= urllib.parse.urljoin( settings.MEDIA_URL, slugifiedFilename)
data= json.dumps( {"location": url})
return HttpResponse( data, content_type='application/json')
Attention:
Beware of the #csrf_exempt. It could be a security risk. See the django documentation for further information.
I have been trying to load a photo onto a Tkinter canvas but I keep failing to do so. The message I get is: TclError: couldn't open "C:\Jules\...\photo_files•0651442_51c04521d6.gif": no such file or directory.
I am using Python 2.7.
Here is my code.
import Tkinter
topthree = Tkinter.Tk()
canvas = Tkinter.Canvas(topthree, height=800, width= 800)
canvas.grid(row = 0, column = 0)
photo = Tkinter.PhotoImage(file = "C:\Jules\...\6250651442_51c04521d6.gif")
im = canvas.create_image(0,0, image=photo)
canvas.pack()
topthree.mainloop()
Prepend r before the file name:
photo = Tkinter.PhotoImage(file = r"C:\Jules\...\6250651442_51c04521d6.gif")
This is because the backslash interprets the next char as a control char, and this can cause some chars to disappear. For example, \n becomes a new line and the n goes away...
Writing r before the string cancels control characters. (r stands for raw string)
I am using audiofield in my Django application to allow upload of a .wav file and render it for play.
I am able to succesfully implement it for one upload at a time, showing the player for a single uploaded file
The code is :
def bottom_player(self):
if self.a_file:
file_url = settings.MEDIA_URL + str(self.a_file)
Html5_string = '<div style="position:fixed; top:5em; right:5em; height: 5em; background-color:white;"><audio controls><source src="%s" type="audio/mpeg">%s Your browser does not support the audio element.</audio><br><h3>Audio player will adjust to your screen</h3></div>' % (file_url, os.path.basename(self.a_file.name))
return Html5_string
bottom_player.allow_tags = True
Now, I want to show separate player for multiple uploaded files, so I have created another table having a_file field for upload and a SQL trigger to copy the newly created a_file field value to the previous a_file column in comma separated format
audio-file-NACHY-1698934831.wav, ./audio-file-ABGYT-1890930931.wav
To parse this a_file column values and then show player for each path, the code looks like:
def bottom_player(self):
if self.a_file:
audiolist = self.a_file
filenamelist = audiolist.split(",")
filenamelist
for filename in filenamelist:
file_url = settings.MEDIA_URL + str(filename)
Html5_string += '<div style="position:fixed; top:5em; right:5em; height: 5em; background-color:white;"><audio controls><source src="%s" type="audio/mpeg">%s Your browser does not support the audio element.</audio><br><h3>Audio player will adjust to your screen</h3></div>' % (file_url, os.path.basename(self.filename))
return Html5_string
bottom_player.allow_tags = True
I get "None" in my bottom player field in the Django page.
Update 2:
I am still fighting to get the Icon save on the server.
Here what I am doing:
Item item = Sitecore.Context.Database.GetItem(imageId);
var imageIconUrl = Sitecore.Resources.Images.GetThemedImageSource(item.Appearance.Icon, ImageDimension.id32x32);
if (!string.IsNullOrEmpty(imageIconUrl))
{
// download the icon from the url
var iconFullPath = "e:\\pngIcons\\excelIcon.png";
var webClient = new System.Net.WebClient();
var downloadPath = "http://serverName/" + imageIconUrl;
webClient.DownloadFile(downloadPath, iconFullPath);
}
The variable downloadPath contains following string:
http://serverName/sitecore/shell/themes/standard/~/media/E503BA48C89B422D8400393F1C7086A7.ashx?h=32&thn=1&w=32&db=master
At the end what I can see is a png file but there is nothing in it. I also copy the string I get in variable downloadPath and pasted it in browser and I can see the Icon as follow:
Please let me know what I am doing wrong. Or How I can save the Icon. Thanks!!
Original Question:
The sitecore media item has a field "Media". I am talking about this:
I want to access this field. And the reason is:
If I access it with e.g. item.GetMediaStream() then I will get the complete file. I just want to save this little icon some how on the server. Is it possible ?
To get the icon/thumbnail you can use
var icon = Sitecore.Resources.Media.MediaManager.GetThumbnailUrl(mediaItem);
To get the url of the thumbnail.
If you want the stream of the thumbnail you need to use the MediaData object. Like this:
var mediaItem = new MediaItem(item)
var mediaData = new MediaData(mediaItem);
var iconStream = mediaData.GetThumbnailStream();
if (iconStream.Length < 0)
{
// The stream is empty, its probably a file that Sitecore can't
// generate a thumbnail for. Just use the Icon
var icon = item.Appearance.Icon;
}
This will get the icon or thumbnail of the actual media blob that is attached to the media item. If you just want the icon of the Sitecore item, then use Martins method.
If the stream is empty, then Sitecore can't generate a thumbnail for it, so you can just use the icon file for the media item template. item.Appearance.Icon
Appearance section (of Standard Template) has a field called Icon - this is where you can modify icon for the item. There is also a field called Thumbnail - your excel icon is sitting there
You can access the field programmatically, just mind that it starts with two underscores: __Icon:
var iconField = item.Fields["__Icon"];
var thumbnailField = item.Fields["__Thumbnail"];
Update: As you asked, below is the code that saves either of fields into the file on a drive. I have tested the code and confirm successfully stores icon from thumbnail field into the file:
string mediaItemPath = "/sitecore/media library/Files/ExcelFile";
string mediaFiedlName = "Thumbnail"; // also can be "__Icon"
var item = Sitecore.Context.Database.GetItem(mediaItemPath);
var iconField = item.Fields[mediaFiedlName];
if (iconField.HasBlobStream)
{
var thumb = (ImageField)iconField;
var bl = ((MediaItem)thumb.MediaItem).InnerItem.Fields["blob"];
Stream stream = bl.GetBlobStream();
byte[] buffer = new byte[8192];
using (FileStream fs = File.Create("D:\\you_file_name.ico")) // change your path
{
int length;
do
{
length = stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, length);
}
while (length > 0);
fs.Flush();
fs.Close();
}
}
Update 2: If that does not help then I would advise to look around the way how that icon gets generated on Media field in Sitecore. In the worst case you may do the following - right click that icon and see its url. You will have something similar to what I assign to variable below:
string url = "http://test81/sitecore/shell/Applications/-/media/B4F61650CBE84EE396649602C0C48E1B.ashx?bc=White&db=master&h=128&la=en&mw=640&thn=1&vs=1&ts=b8046903-ae57-4f9d-9dd5-b626ee5eee90";
Of course your URL should have your hostname and media prefix and the rest of parameters. Then use Webclient with that modified URL:
WebClient webClient = new WebClient();
webClient.DownloadFile(url, "e:\\you_file_name.ico");
Not ideal, but may work. Note, that the code above should work in a context of already logged user, so you need to authorise you Webclient prior that (many articles on S.O. how to do that).
Please reply if that approach has worked for you (I've spent decent time writing and testing that code in debugger, so would want to know whether that helped)
I have successfully used photos.upload api to upload local images to the users album.
How to upload local images with formatted links? The photos.upload does support adding the caption text, but I can't embed html-links to the caption. Is there a way to do this using perhaps the Graph-api?
I'm not sure about the caption itself, but here is a way to post the image along with a message to the user's wall. The message text can have imbedded links in it with no problem.
Facebook* fb = [(AppDelegate *) [[UIApplication sharedApplication] delegate] facebook];
NSData* imageData = UIImageJPEGRepresentation([UIImage imageNamed: #"A.jpg"], 90);
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys: [fb accessToken],
#"access_token",
#"some message here...with a link http://www.google.com",
#"message",
imageData,
#"source",
nil];
[fb requestWithGraphPath: #"me/photos"
andParams: params
andHttpMethod: #"POST"
andDelegate: self];