Summernote Image Uplaod With Spatie Media Library On Livewire - laravel-livewire

I'm using Laravel Livewire and Summernote editor. I'm using Spatie Media Library for uploaded images on editor.
On my edit page component I've this code:
$dom = new \DomDocument();
$dom->loadHtml($this->pageBody, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$pageImages = $dom->getElementsByTagName('img');
if ($pageImages) {
foreach ($pageImages as $k => $img) {
$data = $img->getAttribute('src');
$this->page->addMediaFromBase64($data)->toMediaCollection('pageImages');
$img->removeattribute('src');
$img->setattribute('src', $this->page->getMedia('pageImages')[$k]->getUrl());
}
}
The problem is, if I click "update" button all images are uploading again in to new subfolders and generating new database records. How can I prevent uploading duplicate files or check before upload from database?

Related

Upload multiple pbix from folder into workspace with a new dataset source

I downloaded multiple power bi's with the same datasource connection. Now i want to upload them into a new Workspace and connect them with the new dataset source id.
My current upload code in powershell uploads them into the new workspace but are still connected to the dataset in the "old" workspace...
Some brainstorm:
First i would upload the dataset into the new workspace
get the Dataset Id
and last upload the pbix reports and define the dataset source with the new id
Does anybody have an idea how to do this?
Thank you!!
------- My upload code:
$workspaceName = "MyWorkspace"
$workspace = Get-PowerBIWorkspace -Name $workspaceName
$PBIFilePath = "My\Path\...\"
ForEach($ReportName in Get-ChildItem $PBIFilePath -Filter *.pbix)
{
Write-Host "------ Uploading " $ReportName
$FullPath = $PBIFilePath + $ReportName
$import = New-PowerBIReport -Path $FullPath -Workspace $workspace -ConflictAction CreateOrOverwrit
}
Write-Host "------------------Done------------------"
That's called "report rebind", see the Reports - Rebind Report In Group API.
On the doc page there's a "Try it out" button where you can fill in a form and make the call. In this case POST
{
datasetId: "<datasetId>"
}
to
https://api.powerbi.com/v1.0/myorg/groups/<workspaceId>/reports/<reportId>/Rebind
With headers
Authorization: Bearer eyJ0eXAiOiJKV1QiL...H66IKh8dfDA
Content-type: application/json

How can I allow large file uploads on Django

I have a website www.theraplounge.co that allows users to upload videos. The problem is our limit on file sizes are to small. How can I increase the file size users are able to upload through my forms.py FileField? By the way I’m currently using Amazon S3.
You should be able to configure it via DATA_UPLOAD_MAX_MEMORY_SIZE or/and FILE_UPLOAD_MAX_MEMORY_SIZE setting attributes (remember that you should give the value in bytes).
Check it out:
https://docs.djangoproject.com/en/4.0/ref/settings/#std-setting-DATA_UPLOAD_MAX_MEMORY_SIZE
https://docs.djangoproject.com/en/4.0/ref/settings/#std-setting-FILE_UPLOAD_MAX_MEMORY_SIZE
The problem here is heroku 30 second timeout as i found large files upload on development server but not the production server. The solution would be to upload the files in the front-end using javascript as it doesn't load the browser. I am currently trying to use Javascript AWS SDK to upload video files in the front-end. I got the code to work on small files under 30MB but i face the problem of uploading large files. Posting the working Javascript AWS SDK code below:
<div>
<input type="file" id="fileUpload">
</div>
<div>
<button onclick="s3upload()">Submit</button>
</div>
<script type="text/javascript">
function s3upload() {
AWS.config.region = 'us-east-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'MY-COGNITO-CREDITIONS',
});
var files = document.getElementById('fileUpload').files;
if (files)
{
var file = files[0];
var fileName = file.name;
var fileUrl = 'https://theraplounge.s3.amazonaws.com/' + fileName;
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {
Bucket: 'MY-BUCKET-NAME',
Key: fileName,
Body: file,
};
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var options = {partSize: 5 * 1024 * 1024, queueSize: 1};
s3.upload(params, options, function(err, data) {
if(err) {
alert('error');
} else{
alert('uploaded suceessfully')
};
});
console.log(s3)
}
};
</script>
This is the right approach as it doesn't load the browser at all but i cant get it to upload large files. Once I do find working Javascript code to upload large files I'll update this answer.
Edit:
My problem with uploading large files was my cors policy at Amazon AWS. But also when launched to production I found that Javascript AWS SDK does load the browser and bypass heroku 30 timeout. So I added some knowledge to the process and created a two step form upload process that pass the videos s3 url to another view which would reset the 30s timeout and upload the other information. Test it out on my site www.theraplounge.co/ I manually set the max file size to 500MB but I could be more.

CKFinder when inserting images via drag and drop (Incorrect server response)

I'm trying to use CKFinder 2.6.3 from this site (https://ckeditor.com/ckfinder/download/) with CKEditor and I'm getting an error when using drag and drop. It says "Incorrect server response." I can use the Browse Server and the upload functions but the drag and drop is the only thing giving the error.
I am using the example that was provided in the CKFinder download:
<script src="//cdn.ckeditor.com/4.5.6/standard-all/ckeditor.js"></script>
<script>
if ( typeof CKEDITOR !== 'undefined' ) {
CKEDITOR.addCss( 'img {max-width:100%; height: auto;}' );
var editor = CKEDITOR.replace( 'editor1', {
extraPlugins: 'uploadimage,image2',
removePlugins: 'image',
height:350
} );
CKFinder.setupCKEditor( editor, '../' ) ;
} else {
document.getElementById( 'description' ).innerHTML = '<div class="tip-a tip-a-alert">This sample requires working Internet connection to load CKEditor from CDN.</div>'
}
</script>
In the console, it says:
ckeditor.js:19 [CKEDITOR] Error code: filetools-response-error.
{responseText: "//{"uploaded":1,"error":{"message":"A file with th…ncements\/images\/2367_093051_750_589115(1).jpg"}"}
responseText: "//{"uploaded":1,"error":{"message":"A file with the same name is already available. The uploaded file was renamed to \"2367_093051_750_589115(1).jpg\".","number":201},"fileName":"2367_093051_750_589115(1).jpg","url":"\/pictures\/Announcements\/images\/2367_093051_750_589115(1).jpg"}"
__proto__: Object
I have read in some posts that you have to specify responseType=json but I'm not sure where to put that.
For anyone who might be having this issue. RRK pointed out that there is an option in the Coldfusion Administrator for "Prefix serialized JSON with //". I unchecked this option and it resolved the issue for me.

Uploaded media files 404 on production but show up hours later

We've built a custom front end for users to post threads and upload images on top of Sitecore 9. Recently, we moved the user generated content to it's own database, so the media files are no longer in the proper sitecore 'media gallery'. Also, file storage is on a networked share. Uploading images works just fine. It's immediately after where the problem lies.
Upon image upload, our rest api returns the media url from the MediaManager.GetMediaUrl(itemId). This also works. It returns a valid url, it is formatted correctly and should resolve. Unfortunately, for some time after, the url does the sitecore dance an 302s to our 404 page.
I can see the image through the content editor and our custom content handler injects the image folder node into both master and web databases.
Why would the link manager be able to find the url, but the image is not available? I uploaded something yesterday afternoon, an when I checked this morning, the image is now available on the site. Any information or suggestions are appreciated.
I have tried saving the image multiple times hoping that this might trigger whatever mystical Sitecore event that causes images to show. Since there isn't a publish due to the separate database, I can't try that. I've removed all versions thinking it couldn't default to a particular language. Nothing. Only time seems to make the images visible. The code below works just fine. I'm just putting it here to to show some work.
public MediaItem UploadSimpleMedia(MediaGallerySimpleUploadRequest request)
{
try
{
var destinationFolder = request.ParentItemId != null
? _content.GetItem<Item>(request.ParentItemId.Value)
: _content.GetItem<Item>(_publicLibraryPath + "/embeded");
var name = !string.IsNullOrEmpty(request.Name)
? ItemUtil.ProposeValidItemName(request.Name)
: ItemUtil.ProposeValidItemName(request.Files[0].FileName);
var creator = new MediaCreator();
var tags = request.Tags != null ? request.Tags.Split(',') : new string[0];
var tagIds = _tagService.GetTagIds(tags);
var tagIdString = string.Join(",", tagIds);
var options = new MediaCreatorOptions()
{
AlternateText = request.Name,
FileBased = true,
IncludeExtensionInItemName = false,
Versioned = false,
Destination = $"{destinationFolder.Paths.Path}/{name}",
Database = Factory.GetDatabase("content")
};
using (new SecurityDisabler())
using (new DatabaseCacheDisabler())
{
MediaItem item = creator.CreateFromStream(request.Files[0].InputStream, request.Files[0].FileName, options);
item.BeginEdit();
item.InnerItem["Title"] = request.Name;
item.InnerItem["Description"] = request.Description;
item.InnerItem["__Semantics"] = tagIdString;
// Sitecore won't calculate MIME Type or File Size automatically unless you upload directly
// to the Sitecore Media Library. We're uploading in-place for private groups for permission inheritance
// and now because of indexing, they are getting uploaded to /Community/Gallery/Files if not private.
item.InnerItem["Size"] = request.Files[0].ContentLength.ToString();
item.InnerItem["Mime Type"] = request.Files[0].ContentType;
item.EndEdit();
// Just pausing here to reflect on why Sitecore is so sexily complicated
// that it takes time to display an image on the CD, but has no problem giving
// up the media url
CacheManager.GetHtmlCache(Sitecore.Context.Site);
_searchService.RefreshIndex(item.ID.Guid);
var fromDatabase = _content.GetItem<Item>(item.ID.Guid);
return fromDatabase;
}
}
catch (Exception ex)
{
_logger.Error(this.GetType().AssemblyQualifiedName, ex);
_logger.Trace(ex.StackTrace);
}
return null;
}
I don't get any error messages either in our custom logs or the default sitecore logs. Images just aren't resolving. Is it caching? I've even nuked all caches by calling CacheManager.ClearAllCaches().

how to change host web url from sharepoint provider hosted app

I want to change url of host web from provider hosted app.
Basically, after completion of some business logic in my provider hosted app, I want to navigate to another page of SharePoint portal (for example the search-center page).
When I do "response.redirect" or "window.location.href" it is loading within the App iframe. I want to load the same page in main window.
Please suggest.
Updating with my logic
I have a generic method to get List home page url
public string ListHomePage(ClientContext clientContext, string listName)
{
Web spWeb = clientContext.Web;
clientContext.Load(spWeb, web => web.Url);
clientContext.ExecuteQuery();
return TokenHelper.GetAppContextTokenRequestUrl(spWeb.Url, HttpContext.Current.Server.UrlEncode(spWeb.Url + "/Lists/" + listName));
}
and I am calling following code in App page.
Response.Redirect(ListHomePage(clientContext1, "Test ListName"));
The same can be achieved using below code as the AppPart loads inside a iframe
string redirectUrl = ListHomePage(clientContext1, "Test ListName");
string script = "<script type='text/javascript'>window.parent.location.href = '" + redirectUrl + "'; </script>";
//Here I am using Telerik ScriptManager to execute script
RadScriptManager.RegisterStartupScript(this, this.GetType(), "Load", script, false);