Browse Source

Fixed image upload for firefox, added image usage from Universal Storage, fixed database copy error

Manuel Gall 3 years ago
parent
commit
0147b55f9a
7 changed files with 184 additions and 32 deletions
  1. BIN
      server/database/stations.db
  2. 36 6
      server/was.rb
  3. 8 0
      server/was.xml
  4. 15 0
      ui/imageReplacement.php
  5. 6 1
      ui/index.html
  6. 66 1
      ui/js/design.js
  7. 53 24
      ui/js/imageUpload.js

BIN
server/database/stations.db


+ 36 - 6
server/was.rb

@@ -91,7 +91,7 @@ end
 
 class CreatePattern < Riddl::Implementation
   def response
-    
+
     doc = Nokogiri::XML(@p[0].value)
     result = $db.execute "SELECT MAX(patternID) FROM station"
     if(result[0][0] == nil)
@@ -184,7 +184,7 @@ class DuplicatePattern < Riddl::Implementation
     
     #duplicate image db
     result = $db.execute "SELECT * FROM image WHERE station = #{@r[0]} and patternID = #{@r[1]}"
-    if(result[0][1] != nil)
+    if(result[0] != nil)
       result.each do |row|
         row[1] = id;
         questionmarks = ""
@@ -203,7 +203,7 @@ class DuplicatePattern < Riddl::Implementation
     
     #duplicate Replacement db
     result = $db.execute "SELECT * FROM replacements WHERE station = #{@r[0]} and patternID = #{@r[1]}"
-    if(result[0][1] != nil)
+    if(result[0] != nil)
       result.each do |row|
         row[1] = id;
         questionmarks = ""
@@ -308,9 +308,7 @@ class UploadImage < Riddl::Implementation
   def response
     
     lang = @p[@p.length-1].value
-    
-    $db.execute "CREATE TABLE IF NOT EXISTS image(station INT, patternID INT, imageID INT, language CHARACTER(20), label TEXT, FOREIGN KEY(station) REFERENCES station(station), FOREIGN KEY(patternID) REFERENCES station(patternID),PRIMARY KEY(station,patternID,imageID,language))"
-    
+        
     result = $db.execute "SELECT MAX(imageID) FROM image WHERE station = #{@r[0]} and patternID = #{@r[1]} and language = '#{lang}'"
     if(result[0][0] == nil)
       id = 0
@@ -343,6 +341,37 @@ end
 
 
 
+class AddExternalImage < Riddl::Implementation
+  def response
+    
+    doc = Nokogiri::XML(@p[0].value)
+    url = doc.xpath("/externalImage/url").text
+    lang = doc.xpath("/externalImage/lang").text   
+          
+    result = $db.execute "SELECT MAX(imageID) FROM image WHERE station = #{@r[0]} and patternID = #{@r[1]} and language = '#{lang}'"
+    if(result[0][0] == nil)
+      id = 0
+      else
+      id = result[0][0] +1
+    end
+    
+    #Create link file (we create a file so moving/deleting works always the same and the database does not have to be changed for external files) only thing that had to be changed was imgReplacement.php          
+    image = '<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" overflow="hidden">  <image href="' + url +'" height="100%" width="100%"/>
+    </svg>'
+    
+    path = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], id.to_s)
+    File.open(File.join(path, lang + ".svg"), 'wb') do |file|
+      file.write(image)
+    end
+    
+    #Create DB entry as usual
+    $db.execute("INSERT INTO image (station, patternID, imageID, language, label) VALUES (?,?,?,?,?)", [@r[0], @r[1], id, lang,  url])
+    
+  end
+end
+
+
+
 class ReorderImages < Riddl::Implementation
   def response
     
@@ -1011,6 +1040,7 @@ server = Riddl::Server.new(File.join(__dir__,'/was.xml'), :host => 'localhost')
         on resource 'images' do
           run GetImages if get
           #run CreateImage if post #'image'
+          run AddExternalImage if post 'externalImage'
           run UploadImage if post
           on resource 'reorder' do
             on resource do

+ 8 - 0
server/was.xml

@@ -87,6 +87,13 @@
       <xi:include href="rngs/t_errors.rng"/>
     </parameter>
   </message> <!--}}}-->
+  <message name="externalImage"> <!--{{{-->
+    <parameter name="externalImage" mimetype="*/xml" handler="http://riddl.org/ns/handlers/relaxng">
+      <xi:include href="rngs/t_externalImage.rng"/>
+    </parameter>
+  </message> <!--}}}-->
+  
+  
   
   
   <resource>
@@ -111,6 +118,7 @@
           </resource>
           <resource relative="images">
             <get out="images"/>
+            <post in="externalImage" />
             <post />
             <post in="imageUpload"/>
             <resource relative="reorder">

+ 15 - 0
ui/imageReplacement.php

@@ -14,6 +14,21 @@
   $svg_file = file_get_contents(dirname(__DIR__, 1) . "/images/uploads/" . $_GET["___image___"]);
   
   
+  $doc1 = new DOMDocument;
+  $doc1->loadXML($svg_file);
+  $xpath1 = new DOMXPath($doc1);
+  $xpath1->registerNamespace('svg', 'http://www.w3.org/2000/svg');
+  
+  
+  
+  //prüfen ob exteranlImage dann wird dieses verwendet
+  if(strlen($svg_file) < 400){
+    $url = $xpath1->query("/svg:svg/svg:image/@href");
+    $svg_file  = file_get_contents($url[0]->nodeValue);
+  }
+  
+  
+  
   $doc = new DOMDocument;
   $doc->loadXML($svg_file);
   $xpath = new DOMXPath($doc);

+ 6 - 1
ui/index.html

@@ -175,7 +175,7 @@
                   <table style="width:100%">
                     <tr>
                       <td class="handle">⇅</td>
-                      <td data-class='image'></td>
+                      <td data-class='image' class="image"></td>
                     </tr>
                   </table>
                 </div>
@@ -216,6 +216,11 @@
                   </div>
                   <div class="box__error">Error! <span></span>.</div>
                 </form>
+                
+                
+                <input type="text" class="abbreviationInput width100 url" name="externalImage" id="addExternalImageUrl">
+                <a href="#" onclick="overlayOn($(this));">🔍</a> <a href="#" onclick="addExternalImage();" id="addExternalImage">add Image</a>
+                
               </div>
             </div>
           </div>

+ 66 - 1
ui/js/design.js

@@ -378,6 +378,12 @@ function getImages(stationID, patternID){ //Get From DB 2 HTML
   $('#imgUpload').attr("action", "../server/" + stationID + "/" + patternID + "/images");
   
   
+  
+
+
+  $('#addExternalImage').attr("onclick", "addExternalImage(" + stationID + "," + patternID + ")");
+  
+  
   $.ajax({
 	  type: "GET",
 	  url: "../server/"+stationID+ "/" + patternID + "/images",
@@ -395,7 +401,26 @@ function getImages(stationID, patternID){ //Get From DB 2 HTML
             
             var imgsrcsingle = "../images/uploads/"+stationID+ "/" + patternID + "/" + curID + "/"+ $(this).attr('lang') + ".svg";
             var imgsrc = imgsrcsingle + "?" + Date.now();
-            $('[data-class=image]',clone).append('<img id="theImg" src="' + imgsrc +'" onclick="overlayOnImg(\'' +imgsrcsingle + '\')" height="100px" />')
+            
+            //$('[data-class=image]',clone).append('<img id="theImg" src="' + imgsrc +'" onclick="overlayOnImg(\'' +imgsrcsingle + '\')" height="100px" />')
+            
+            //$('[data-class=image]',clone).append('<object class="theImg" id="theImg" data="' + imgsrc +'" onclick="overlayOnImg(\'' +imgsrcsingle + '\')" height="100px" />')
+            
+            $('[data-class=image]',clone).load(imgsrc, function(){
+            
+              
+                var width = $(this).children("svg").attr("width")
+                var height = $(this).children("svg").attr("height")
+              
+                $(this).children("svg").attr("viewBox","0 0 " + width + " " + height);
+                $(this).children("svg").attr("width","100");
+                $(this).children("svg").attr("height","100");
+              
+            });
+            
+            
+            //$('[data-class=image]',clone).append('<div style="background-image: url(' + imgsrc+ ')" height="100px" />')
+            
             $('[data-class=label]',clone).val($(this).attr('label'));
             $('[data-class=label]',clone).attr("origValue", $(this).attr('label'));			
             $('[data-class=imageId]',clone).text(curID);
@@ -407,14 +432,54 @@ function getImages(stationID, patternID){ //Get From DB 2 HTML
         });
       });
 	    $('#image_count').text(count);
+      
+      
+      
+      /*
+      $(".image").each(function() {
+        alert("mhm");
+        
+        
+        
+        $(this).children().attr("viewBox","0 0 " + "300" + " 300");
+      
+      });
+      */
+      
     }
   });
+  
+  
+  
+  
   new Sortable(document.getElementById('imageListing'),{
 	  handle: '.handle',
 	  animation: 150
   });
 }
 
+function addExternalImage(stationID, patternID){
+  
+  
+  var extImage = $.parseXML("<externalImage/>");
+  $(extImage).find("externalImage").append("<url>" + $('#addExternalImageUrl').val() +"</url>");
+  $(extImage).find("externalImage").append("<lang>" + $('#image_language option:selected').text() + "</lang>");
+  
+  
+  $.ajax({
+    type: "POST",
+    headers: {"content-id": "externalImage"},
+    data: (new XMLSerializer()).serializeToString(extImage),
+    contentType: "application/xml; charset=utf-8",
+    url: "../server/" + stationID + "/" + patternID + "/images",
+    success: function(res) {
+      getPattern(stationID, patternID)	 
+    }
+  }); 
+  
+  
+}
+
 function deleteImage(stationID, patternID, imageID, lang) { //Delete From DB
   $.ajax({
     type: "DELETE",

+ 53 - 24
ui/js/imageUpload.js

@@ -25,9 +25,10 @@ function imageInit(){
 				},
 				triggerFormSubmit = function()
 				{
-					var event = document.createEvent( 'HTMLEvents' );
-					event.initEvent( 'submit', true, false );
-					form.dispatchEvent( event );
+          $('#imgUpload').submit(); 
+					//var event = document.createEvent( 'HTMLEvents' );
+					//event.initEvent( 'submit', true, false );
+					//form.dispatchEvent( event );
 				};
 
 			// letting the server side to know we are going to make an Ajax request
@@ -40,12 +41,8 @@ function imageInit(){
 			// automatically submit the form on file select
 			input.addEventListener( 'change', function( e )
 			{
-				showFiles( e.target.files );
-
-				
-				triggerFormSubmit();
-
-				
+				showFiles( e.target.files );				
+				triggerFormSubmit();				
 			});
 
 			// drag&drop files if the feature is available
@@ -83,18 +80,16 @@ function imageInit(){
 
 					
 					triggerFormSubmit();
-
+          e.dataTransfer.files = [];
 									});
 			}
 
 
 			// if the form was submitted
-			form.addEventListener( 'submit', function( e )
-			{
-				
+      
+      $('#imgUpload').submit(function(e){
 				// preventing the duplicate submissions if the current one is in progress
 				if( form.classList.contains( 'is-uploading' ) ) return false;
-
 				form.classList.add( 'is-uploading' );
 				form.classList.remove( 'is-error' );
 				
@@ -126,10 +121,31 @@ function imageInit(){
 					ajaxData.append("language", language)
 					
 					
+           
+          /*
+          $.ajax({
+            type: "POST",
+            url: form.getAttribute( 'action' ),
+            headers: {"content-id": "pattern"},
+            data: ajaxData,
+            contentType: false,
+            processData: false,
+            success: function(res) {
+              getPattern(station, pattern)
+              input.value = "";                
+            },
+            error: function (request, status, error) {
+              alert(request.responseText + status + error);
+            }
+          });
+          */
+          
+          //Original Upload:
+          
 					// ajax request
 					var ajax = new XMLHttpRequest();
-					ajax.open( form.getAttribute( 'method' ), form.getAttribute( 'action' ), true );
-
+					ajax.open( form.getAttribute( 'method' ), form.getAttribute( 'action' ), false );
+          
 					ajax.onload = function()
 					{
 						form.classList.remove( 'is-uploading' );
@@ -138,15 +154,11 @@ function imageInit(){
 							getPattern(station, pattern)
 							
 							input.value = "";
+              //imageInit();
 							//form.classList.add('is-success');
 							
 							//old upload php: saveImages(station, pattern, curCount, language, ajax.responseText);
 							
-							/*
-							var data = JSON.parse( ajax.responseText );
-							form.classList.add( data.success == true ? 'is-success' : 'is-error' );
-							if( !data.success ) errorMsg.textContent = data.error;
-							*/
 						}
 						else alert( 'Error. Please, contact the webmaster!' );
 					};
@@ -156,12 +168,22 @@ function imageInit(){
 						form.classList.remove( 'is-uploading' );
 						alert( 'Error. Please, try again!' );
 					};
-
 					ajax.send( ajaxData );
-		            imageInit();
+          
+          
+          
+          form.classList.remove( 'is-uploading' );
+					form.classList.remove( 'is-error', 'is-success' );
+          
+          e.target.files = [];
+					input.value = "";
+          droppedFiles = false;
+          
+          
 				}
 				else // fallback Ajax solution upload for older browsers
 				{
+          
 					var iframeName	= 'uploadiframe' + new Date().getTime(),
 						iframe		= document.createElement( 'iframe' );
 
@@ -183,6 +205,14 @@ function imageInit(){
 						iframe.parentNode.removeChild( iframe );
 					});
 				}
+        
+        /*
+        if(e.preventDefault){ e.preventDefault()}
+        else{e.stop()};
+
+        e.returnValue = false;
+        e.stopPropagation();
+        */
 			});
 
 
@@ -200,7 +230,6 @@ function imageInit(){
 			// Firefox focus bug fix for file input
 			input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); });
 			input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });
-
 		});
 }