was.rb 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. #!/usr/bin/ruby
  2. #
  3. # This file is part of centurio.work/ing/commands.
  4. #
  5. # centurio.work/ing/commands is free software: you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or (at your
  8. # option) any later version.
  9. #
  10. # centurio.work/ing/commands is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  13. # Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License along with
  16. # centurio.work/ing/commands (file COPYING in the main directory). If not, see
  17. # <http://www.gnu.org/licenses/>.
  18. require 'rubygems'
  19. require 'json'
  20. require 'riddl/server'
  21. require 'riddl/client'
  22. require 'fileutils'
  23. require 'nokogiri'
  24. require 'sqlite3'
  25. require 'net/http'
  26. require 'uri'
  27. $db = SQLite3::Database.open 'database/stations.db'
  28. class GetJsonFiles < Riddl::Implementation
  29. def response
  30. Dir.chdir( __dir__ + '/json')
  31. ret = [];
  32. Dir.glob('*').select{ |e|
  33. ret.append(e)
  34. }
  35. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  36. end
  37. end
  38. class GetJson < Riddl::Implementation
  39. def response
  40. Dir.chdir( __dir__ + '/json')
  41. Riddl::Parameter::Complex.new('list','application/json',File.open(@r[1]).read) rescue Riddl::Parameter::Complex.new('list','application/json', '{"error":"No such file"}')
  42. end
  43. end
  44. class SaveJson < Riddl::Implementation
  45. def response
  46. Dir.chdir( __dir__ + '/json')
  47. File.write(@r.last,(@p[0].value.read))
  48. end
  49. end
  50. class GetStations < Riddl::Implementation
  51. def response
  52. result = $db.execute "SELECT * FROM stations"
  53. builder = Nokogiri::XML::Builder.new do |xml|
  54. xml.stations {
  55. result.each do |row|
  56. xml.station(:id => row[0]){
  57. resultstation = $db.execute "SELECT * FROM stationpattern WHERE station = #{row[0]}"
  58. resultstation.each do |row|
  59. xml.pattern(:id => row[1], :description => row[2], :changed => row[3]){
  60. xml.parts{
  61. resultpattern = $db.execute "SELECT * FROM pattern WHERE internalID = #{row[1]}"
  62. resultpattern.each do |row2|
  63. xml.send(row2[1], row2[2])
  64. end
  65. }
  66. }
  67. end
  68. }
  69. end
  70. }
  71. end
  72. #puts builder.to_xml
  73. Riddl::Parameter::Complex.new('stations','application/xml',builder.to_xml)
  74. end
  75. end
  76. class CreateStation < Riddl::Implementation
  77. def self::createDB(n)
  78. #result = $db.execute "SELECT MAX(station) FROM stations"
  79. #if(result[0][0] == nil)
  80. # $db.execute "INSERT INTO stations (station) VALUES (?)", 0
  81. #else
  82. # $db.execute "INSERT INTO stations (station) VALUES (?)", result[0][0]+1
  83. #end
  84. #$db.execute ("INSERT INTO stations (station, name) VALUES (?,?)", [n,n])
  85. $db.execute("INSERT OR IGNORE INTO stations (station, name) VALUES (?,?)", [n,n])
  86. end
  87. def response
  88. GetStation::createDB
  89. end
  90. end
  91. class GetStation < Riddl::Implementation
  92. def self::prepare(id)
  93. resultstation = $db.execute "SELECT * FROM stationpattern WHERE station = #{id}"
  94. Nokogiri::XML::Builder.new do |xml|
  95. xml.station(:id => id){
  96. resultstation.each do |row|
  97. xml.pattern(:id => row[1], :description => row[2], :changed => row[3]){
  98. xml.parts{
  99. resultpattern = $db.execute "SELECT * FROM pattern WHERE internalID = #{row[1]}"
  100. resultpattern.each do |row2|
  101. xml.send(row2[1], row2[2])
  102. end
  103. }
  104. }
  105. end
  106. }
  107. end
  108. end
  109. def response
  110. builder = GetStation::prepare(@r.last)
  111. Riddl::Parameter::Complex.new('station','application/xml',builder.to_xml)
  112. end
  113. end
  114. class CreatePattern < Riddl::Implementation
  115. def response
  116. doc = Nokogiri::XML(@p[0].value)
  117. result = $db.execute "SELECT MAX(internalID) FROM stationpattern"
  118. if(result[0][0] == nil)
  119. id = 0
  120. else
  121. id = result[0][0] +1
  122. end
  123. $db.execute("INSERT INTO stationpattern (station, internalID, description, date) VALUES (?,?,?,?)", [@r.last, id, doc.xpath("/*/@description")[0].value, doc.xpath("/*/@changed")[0].value])
  124. doc.xpath(".//parts/*").each do |node|
  125. #if(node.text != "")
  126. $db.execute("INSERT INTO pattern (internalID, type, value) VALUES (?,?,?)", [id, node.name, node.text])
  127. #end
  128. end
  129. ret = {:id => id}
  130. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  131. end
  132. end
  133. class GetPattern < Riddl::Implementation
  134. def response
  135. resultstation = $db.execute "SELECT * FROM stationpattern WHERE station = #{@r[0]} AND internalID = #{@r[1]}"
  136. builder = Nokogiri::XML::Builder.new do |xml|
  137. resultstation.each do |row|
  138. xml.pattern(:id => row[1], :description => row[2], :changed => row[3]){
  139. xml.parts{
  140. resultpattern = $db.execute "SELECT * FROM pattern WHERE internalID = #{row[1]}"
  141. resultpattern.each do |row2|
  142. xml.send(row2[1], row2[2])
  143. end
  144. }
  145. }
  146. end
  147. end
  148. Riddl::Parameter::Complex.new('pattern','application/xml',builder.to_xml)
  149. end
  150. end
  151. class UpdatePattern < Riddl::Implementation
  152. def response
  153. doc = Nokogiri::XML(@p[0].value)
  154. $db.execute("Update stationpattern SET description = ?, date = ? WHERE internalID = ?", [doc.xpath("/*/@description")[0].value, doc.xpath("/*/@changed")[0].value, @r[1]])
  155. $db.execute("DELETE FROM pattern WHERE internalID = ?", [@r[1]])
  156. doc.xpath(".//parts/*").each do |node|
  157. #if(node.text != "")
  158. $db.execute("INSERT INTO pattern (internalID, type, value) VALUES (?,?,?)", [@r[1], node.name, node.text])
  159. #end
  160. end
  161. end
  162. end
  163. class DeletePattern < Riddl::Implementation
  164. def response
  165. $db.execute("DELETE FROM stationpattern WHERE internalID = ?", [@r[1]])
  166. end
  167. end
  168. class DuplicatePattern < Riddl::Implementation
  169. def response
  170. #duplicate db etwas mühsam da der eintrag kopiert werden muss und dabei die unique ID verändert werden muss daher geht insert into select nicht so ganz.
  171. result = $db.execute "SELECT MAX(internalID) FROM stationpattern"
  172. if(result[0][0] == nil)
  173. id = 0
  174. else
  175. id = result[0][0] +1
  176. end
  177. result = $db.execute "SELECT * FROM stationpattern WHERE internalID = #{@r[1]}"
  178. result[0][1] = id;
  179. $db.execute( "INSERT INTO stationpattern values (?,?,?,?)", result[0])
  180. result = $db.execute "SELECT * FROM pattern WHERE internalID = #{@r[1]}"
  181. result.each do |row|
  182. row[0] = id;
  183. $db.execute( "INSERT INTO pattern values (?,?,?)", row)
  184. end
  185. #duplicate error
  186. #$db.execute "CREATE TABLE IF NOT EXISTS error(internalID INT, error TEXT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  187. result = $db.execute "SELECT * FROM error WHERE internalID = #{@r[1]}"
  188. if(result[0] != nil)
  189. result.each do |row|
  190. row[0] = id;
  191. questionmarks = ""
  192. row.length().times{questionmarks = questionmarks + ",?"}
  193. questionmarks[0] = ""
  194. $db.execute( "INSERT INTO error values (#{questionmarks})", row)
  195. end
  196. end
  197. #duplicate image db
  198. #$db.execute "CREATE TABLE IF NOT EXISTS image(internalID INT, imageID INT, language CHARACTER(20), label TEXT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  199. result = $db.execute "SELECT * FROM image WHERE internalID = #{@r[1]}"
  200. if(result[0] != nil)
  201. result.each do |row|
  202. row[0] = id;
  203. questionmarks = ""
  204. row.length().times{questionmarks = questionmarks + ",?"}
  205. questionmarks[0] = ""
  206. $db.execute( "INSERT INTO image values (#{questionmarks})", row)
  207. end
  208. end
  209. #duplicate images
  210. pathorigin = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1])
  211. pathdestination = File.join(File.dirname(__dir__),'images/uploads', @r[0], id.to_s)
  212. if (Dir.exist?(pathorigin))
  213. FileUtils.mkdir_p(pathdestination)
  214. FileUtils.copy_entry pathorigin, pathdestination
  215. end
  216. #duplicate Replacement db
  217. #$db.execute "CREATE TABLE IF NOT EXISTS replacements(internalID INT, abbreviation TEXT, url TEXT, ordering INT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  218. result = $db.execute "SELECT * FROM replacements WHERE internalID = #{@r[1]}"
  219. if(result[0] != nil)
  220. result.each do |row|
  221. row[0] = id;
  222. questionmarks = ""
  223. row.length().times{questionmarks = questionmarks + ",?"}
  224. questionmarks[0] = ""
  225. $db.execute( "INSERT INTO replacements values (#{questionmarks})", row)
  226. end
  227. end
  228. ret = {:id => id}
  229. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  230. end
  231. end
  232. class SaveError < Riddl::Implementation
  233. def response
  234. $db.execute "CREATE TABLE IF NOT EXISTS error(internalID INT, error TEXT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  235. #Delete all, afterwards insert
  236. $db.execute("DELETE FROM error WHERE internalID = ?", [@r[1]])
  237. doc = Nokogiri::XML(@p[0].value)
  238. doc.xpath(".//reason").each do |node|
  239. $db.execute("INSERT INTO error (internalID, error) VALUES (?,?)", [@r[1], node.text])
  240. end
  241. end
  242. end
  243. class GetError < Riddl::Implementation
  244. def response
  245. result = $db.execute "SELECT * FROM error WHERE internalID = #{@r[1]}"
  246. builder = Nokogiri::XML::Builder.new do |xml|
  247. xml.error(){
  248. result.each do |row|
  249. xml.reason row[1]
  250. end
  251. }
  252. end
  253. Riddl::Parameter::Complex.new('error','application/xml',builder.to_xml)
  254. end
  255. end
  256. class SaveReplacement < Riddl::Implementation
  257. def response
  258. # $db.execute "CREATE TABLE IF NOT EXISTS replacements(internalID INT, abbreviation TEXT, url TEXT, ordering INT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  259. #Delete all, afterwards insert
  260. $db.execute("DELETE FROM replacements WHERE internalID = ?", [@r[1]])
  261. order = 0;
  262. doc = Nokogiri::XML(@p[0].value)
  263. doc.xpath(".//item").each do |node|
  264. $db.execute("INSERT INTO replacements (internalID, abbreviation, url, ordering) VALUES (?,?,?,?)", [@r[1], node.xpath(".//abbreviation").text, node.xpath(".//url").text, order])
  265. order += 1
  266. end
  267. end
  268. end
  269. class GetReplacement < Riddl::Implementation
  270. def response
  271. result = $db.execute "SELECT * FROM replacements WHERE internalID = #{@r[1]} ORDER BY ordering ASC"
  272. builder = Nokogiri::XML::Builder.new do |xml|
  273. xml.replacement(){
  274. result.each do |row|
  275. xml.item(){
  276. xml.abbreviation row[1]
  277. xml.url row[2]
  278. }
  279. end
  280. }
  281. end
  282. Riddl::Parameter::Complex.new('replacement','application/xml',builder.to_xml)
  283. end
  284. end
  285. class GetImages < Riddl::Implementation
  286. def response
  287. formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +
  288. Nokogiri::XML::Node::SaveOptions::NO_DECLARATION
  289. #$db.execute "CREATE TABLE IF NOT EXISTS image(internalID INT, imageID INT, language CHARACTER(20), label TEXT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  290. result = $db.execute "SELECT DISTINCT imageID FROM image WHERE internalID = #{@r[1]} ORDER BY imageID ASC"
  291. builder = Nokogiri::XML::Builder.new do |xml|
  292. xml.images(){
  293. result.each do |row|
  294. xml<< GetImage::prepare(@r[0], @r[1], row[0], @a[0][:appconf]["wasurl"]).to_xml( save_with:formatted_no_decl )
  295. end
  296. }
  297. end
  298. Riddl::Parameter::Complex.new('images','application/xml',builder.to_xml)
  299. end
  300. end
  301. class UploadImage < Riddl::Implementation
  302. def response
  303. lang = @p[@p.length-1].value
  304. #$db.execute "CREATE TABLE IF NOT EXISTS image(internalID INT, imageID INT, language CHARACTER(20), label TEXT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  305. result = $db.execute "SELECT MAX(imageID) FROM image WHERE internalID = #{@r[1]} and language = '#{lang}'"
  306. if(result[0][0] == nil)
  307. id = 0
  308. else
  309. id = result[0][0] +1
  310. end
  311. #puts JSON.pretty_generate(@p)
  312. i = 0
  313. while i < @p.length-1 do
  314. item = @p[i]
  315. if(item != nil && item.name == "files[]")
  316. path = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], id.to_s)
  317. FileUtils.mkdir_p(path)
  318. #juergen nach alternative fragen
  319. readFile = File.read(item.value.inspect.to_s[/Tempfile:(.*?)>/m, 1])
  320. File.open(File.join(path, lang + ".svg"), 'wb') do |file|
  321. file.write(readFile.to_s)
  322. end
  323. $db.execute("INSERT INTO image (internalID, imageID, language, label) VALUES (?,?,?,?)", [@r[1], id, lang, "Label"])
  324. id += 1
  325. end
  326. i +=1
  327. end
  328. end
  329. end
  330. class AddExternalImage < Riddl::Implementation
  331. def response
  332. doc = Nokogiri::XML(@p[0].value)
  333. url = doc.xpath("/externalImage/url").text
  334. lang = doc.xpath("/externalImage/lang").text
  335. result = $db.execute "SELECT MAX(imageID) FROM image WHERE internalID = #{@r[1]} and language = '#{lang}'"
  336. if(result[0][0] == nil)
  337. id = 0
  338. else
  339. id = result[0][0] +1
  340. end
  341. #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
  342. 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%"/>
  343. </svg>'
  344. path = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], id.to_s)
  345. FileUtils.mkdir_p(path)
  346. File.open(File.join(path, lang + ".svg"), 'wb') do |file|
  347. file.write(image)
  348. end
  349. #Create DB entry as usual
  350. $db.execute("INSERT INTO image (internalID, imageID, language, label) VALUES (?,?,?,?)", [@r[1], id, lang, url])
  351. end
  352. end
  353. class ReorderImages < Riddl::Implementation
  354. def response
  355. #remove brackets
  356. iter = @p[0].value.read.chop
  357. iter[0] =""
  358. iter = iter.split(",").map(&:to_i)
  359. i = 0
  360. while i < iter.length do
  361. if(i != iter[i])
  362. #swap
  363. path = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], i.to_s)
  364. path2 = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], iter[i].to_s)
  365. tmp = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1])
  366. FileUtils.mv(path + "/" + @r[4] + ".svg", tmp)
  367. FileUtils.mv(path2 + "/" + @r[4] + ".svg", path)
  368. FileUtils.mv(tmp + "/" + @r[4] + ".svg", path2)
  369. #DB Swap
  370. result = $db.execute "SELECT MAX(imageID) FROM image"
  371. if(result[0][0] == nil)
  372. maxImgId = 0
  373. else
  374. maxImgId = result[0][0] +1
  375. end
  376. #Wegen 999999 fragen
  377. #nutze max ID+1 zum tauschen
  378. $db.execute("UPDATE image SET imageID = ? WHERE internalID = ? AND imageID = ? AND language = ?", [maxImgId, @r[1], i, @r[4]])
  379. $db.execute("UPDATE image SET imageID = ? WHERE internalID = ? AND imageID = ? AND language = ?", [i, @r[1], iter[i], @r[4]])
  380. $db.execute("UPDATE image SET imageID = ? WHERE internalID = ? AND imageID = ? AND language = ?", [iter[i], @r[1], maxImgId, @r[4]])
  381. iter.map! do |item|
  382. if(item == i)
  383. iter[i]
  384. else
  385. item
  386. end
  387. end
  388. end
  389. i +=1
  390. end
  391. end
  392. end
  393. class GetImage < Riddl::Implementation
  394. def self::prepare(station, pattern, imageID, wasurl)
  395. result = $db.execute "SELECT * FROM image WHERE internalID = #{pattern} and imageID = #{imageID}"
  396. Nokogiri::XML::Builder.new do |xml|
  397. xml.image(:id => imageID){
  398. result.each do |row|
  399. xml.variant(:lang => row[2], :label => row[3]){
  400. xml.text(wasurl + "images/uploads/#{station}/#{pattern}/#{imageID}/#{row[3]}.svg")
  401. }
  402. end
  403. }
  404. end
  405. end
  406. def response
  407. builder = GetImage::prepare(@r[0], @r[1], @r[3], @a[0][:appconf]["wasurl"])
  408. Riddl::Parameter::Complex.new('image','application/xml',builder.to_xml)
  409. end
  410. end
  411. class UpdateImageLabel < Riddl::Implementation
  412. def response
  413. $db.execute("UPDATE image SET label = ? WHERE internalID = ? AND imageID = ? AND language = ?", [@p[0].value, @r[1], @r[3], @r[4]])
  414. end
  415. end
  416. #Not used, prototype for replacing image serverside
  417. class GetRealImage < Riddl::Implementation
  418. def response
  419. #split on "." and tacke [0] to allow for e.g. de-at.svg
  420. #would lead to error on de.at.svg //should this be fixed? would also lead to error if everything after last "." would be removed in case of only having de.at
  421. #https://centurio.work/customers/evva/was/server/0/0/images/3/de-at?video=xyz
  422. img = File.read(File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], @r[3], @r[4].split(".")[0] + ".svg"))
  423. if false #Currently replacements are done on the client side
  424. if(@p[0].nil?)
  425. puts "Undefined p"
  426. else
  427. if(@p[0].name == "video" && @p[0].value)
  428. xml = Nokogiri.parse img
  429. puts "Width " + xml.xpath("string(//xmlns:image/@width)")
  430. puts "Height " + xml.xpath("string(//xmlns:image/@height)")
  431. #puts "Posi " + xml.xpath("string(//xmlns:clipPath/path/@height)")
  432. puts "Posi " + xml.xpath("string(//xmlns:image/following-sibling::clipPath/@id)")
  433. puts xml.xpath("string(//xmlns:text[starts-with(text(), 'url')])").sub("url=", "")
  434. # text
  435. img = img.sub! "</svg>", '
  436. <g><g transform="translate(562,288),scale(1.35185 1.35185)">
  437. <foreignObject width="480" height="270">
  438. <video width="480" height="270" controls="" autoplay="autoplay" muted="muted" xmlns="http://www.w3.org/1999/xhtml" >
  439. <source src="' + xml.xpath("string(//xmlns:text[starts-with(text(), 'url')])").sub("url=", "") +'" type="video/mp4"/>
  440. </video>
  441. </foreignObject>
  442. </g></g></svg>'
  443. else
  444. @p.each do |item|
  445. unless item.name.nil? || item.value.nil?
  446. img.sub! item.name, item.value
  447. end
  448. end
  449. end
  450. end
  451. end
  452. Riddl::Parameter::Complex.new('theRealImage','image/svg+xml',img)
  453. end
  454. end
  455. class DeleteImage < Riddl::Implementation
  456. def response
  457. File.delete(File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], @r[3] , @r[4] + ".svg")) if File.exist?(File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], @r[3] , @r[4] + ".svg"))
  458. $db.execute("DELETE FROM image WHERE internalID = ? AND imageID = ? AND language = ?", [@r[1], @r[3], @r[4]])
  459. result = $db.execute "SELECT MAX(imageID) FROM image WHERE internalID = #{@r[1]} and language = '#{@r[4]}'"
  460. if(result[0][0] == nil)
  461. id = 0
  462. else
  463. id = result[0][0] +1
  464. end
  465. #reorder if !end gets deleted
  466. if(id == @r[3])
  467. return
  468. else
  469. cur = @r[3].to_i + 1
  470. prev = @r[3].to_i
  471. while cur < id.to_i do
  472. $db.execute("UPDATE image SET imageID = ? WHERE internalID = ? AND imageID = ? AND language = ?", [prev, @r[1], cur, @r[4]])
  473. src = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], cur.to_s, @r[4] + ".svg")
  474. target = File.join(File.dirname(__dir__),'images/uploads', @r[0], @r[1], prev.to_s, @r[4] + ".svg")
  475. FileUtils.mv(src, target)
  476. cur+=1
  477. prev += 1
  478. end
  479. end
  480. end
  481. end
  482. class ListSearch < Riddl::Implementation
  483. def response
  484. ret = {
  485. :imagesWIZAll => "/imagesWIZ?pattern=...",
  486. :imagesWIZSingle => "/imagesWIZ/0..*/?pattern=...",
  487. :errorsWIZ => "/errorsWIZ/"
  488. }
  489. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  490. end
  491. end
  492. class SearchImages < Riddl::Implementation
  493. def response
  494. #https://centurio.work/customers/evva/was/ui/TransformProductCode.php?ProductCode=E.A.PZ.DZ-S.31.31.MP.SEP
  495. pattern = JSON.parse(Net::HTTP.get URI(@a[0][:appconf]["wasurl"] + "ui/TransformProductCode.php?ProductCode=" + @p[0].value))
  496. #Get first key dynamicly and then build sql query
  497. searchstring = "SELECT " + pattern.keys[0] + ".internalID AS ID"
  498. searchstring = searchstring + " FROM " + pattern.map{ |key, val| "pattern " + key}.join(', ')
  499. searchstring = searchstring + " WHERE " + pattern.map{ |key, val| pattern.keys[0] + ".internalID == " + key + ".internalID"}.join(' AND ')
  500. searchstring = searchstring + " AND " + pattern.map{ |key, val| key + ".type == '" + key + "' AND (" + key + ".value == '"+ val +"' or " + key + ".value == '*')"}.join(' AND ') + " ORDER BY ID ASC"
  501. result = $db.execute searchstring;
  502. puts searchstring
  503. #Search for images with one or multiple found patternIDs
  504. ret = []
  505. if result.length > 0
  506. result.each do |item|
  507. result2 = $db.execute "SELECT DISTINCT internalID, imageID FROM image WHERE internalID = #{item[0]} ORDER BY imageID ASC"
  508. result2.each do |item2|
  509. result3 = $db.execute "SELECT DISTINCT station FROM stationpattern WHERE internalID = #{item2[0]} AND station = #{@r[0]}"
  510. if(result3[0] != nil)
  511. ret << @r[0] + "/" + item2[0].to_s + "/" + item2[1].to_s
  512. end
  513. end
  514. end
  515. end
  516. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  517. end
  518. end
  519. class SearchImagesSingle < Riddl::Implementation
  520. def response
  521. pattern = JSON.parse(Net::HTTP.get URI(@a[0][:appconf]["wasurl"] + "ui/TransformProductCode.php?ProductCode=" + @p[0].value))
  522. searchstring = "SELECT " + pattern.keys[0] + ".internalID AS ID"
  523. searchstring = searchstring + " FROM " + pattern.map{ |key, val| "pattern " + key}.join(', ')
  524. searchstring = searchstring + " WHERE " + pattern.map{ |key, val| pattern.keys[0] + ".internalID == " + key + ".internalID"}.join(' AND ')
  525. searchstring = searchstring + " AND " + pattern.map{ |key, val| key + ".type == '" + key + "' AND (" + key + ".value == '"+ val +"' or " + key + ".value == '*')"}.join(' AND ') + " ORDER BY ID ASC"
  526. result = $db.execute searchstring;
  527. count = 0
  528. pattern = 0
  529. image = 0
  530. builder = Nokogiri::XML::Builder.new do |xml|
  531. xml.image(:id => @r[3].to_s){
  532. if result.length > 0
  533. result.each do |item|
  534. result2 = $db.execute "SELECT DISTINCT internalID, imageID FROM image WHERE internalID = #{item[0]} ORDER BY imageID ASC"
  535. result2.each do |item2|
  536. result3 = $db.execute "SELECT DISTINCT internalID, imageID, language, label FROM image WHERE internalID = #{item[0]} and imageID =#{item2[1]}"
  537. result3.each do |item3|
  538. result4 = $db.execute "SELECT DISTINCT station FROM stationpattern WHERE internalID = #{item3[0]} AND station = #{@r[0]}"
  539. if(result4[0] != nil)
  540. if(count == @r[3].to_i)
  541. #ret << @r[0] + "/" + item2[0].to_s + "/" + item2[1].to_s
  542. uri = @a[0][:appconf]["wasurl"] + "ui/imageReplacement.php?___image___=" + @r[0].to_s + "/" + item3[0].to_s + "/" + item3[1].to_s + "/" + item3[2].to_s + ".svg"
  543. @p.each_with_index do |item, index|
  544. if index != 0
  545. uri += "&" + item.name.to_s + "=" + item.value.to_s
  546. end
  547. end
  548. xml.variant(:lang => item3[2].to_s, :label => item3[3].to_s){
  549. xml.text(uri)
  550. }
  551. end
  552. count += 1
  553. end
  554. end
  555. end
  556. end
  557. end
  558. }
  559. end
  560. #https://centurio.work/customers/evva/was/ui/imageReplacement.php?___image___=8/23/0/de-at.svg
  561. #puts builder.to_xml
  562. Riddl::Parameter::Complex.new('image','application/xml',builder.to_xml)
  563. end
  564. end
  565. class SearchErrors < Riddl::Implementation
  566. def response
  567. pattern = JSON.parse(Net::HTTP.get URI(@a[0][:appconf]["wasurl"] + "ui/TransformProductCode.php?ProductCode=" + @p[0].value))
  568. searchstring = "SELECT " + pattern.keys[0] + ".internalID AS ID"
  569. searchstring = searchstring + " FROM " + pattern.map{ |key, val| "pattern " + key}.join(', ')
  570. searchstring = searchstring + " WHERE " + pattern.map{ |key, val| pattern.keys[0] + ".internalID == " + key + ".internalID"}.join(' AND ')
  571. searchstring = searchstring + " AND " + pattern.map{ |key, val| key + ".type == '" + key + "' AND (" + key + ".value == '"+ val +"' or " + key + ".value == '*')"}.join(' AND ') + " ORDER BY ID ASC"
  572. result = $db.execute searchstring;
  573. ret = []
  574. if result.length > 0
  575. result.each do |item|
  576. result2 = $db.execute "SELECT DISTINCT error FROM error WHERE internalID = #{item[0]} ORDER BY internalID ASC"
  577. result2.each do |item2|
  578. ret << item2[0].to_s
  579. end
  580. end
  581. end
  582. ret = ret.uniq
  583. builder = Nokogiri::XML::Builder.new do |xml|
  584. xml.reason{
  585. if result.length > 0
  586. ret.each do |item|
  587. xml.reason(:lang => "de-at"){
  588. xml.text(item)
  589. }
  590. end
  591. end
  592. }
  593. end
  594. Riddl::Parameter::Complex.new('errors','application/xml',builder.to_xml)
  595. end
  596. end
  597. class GetAssignments < Riddl::Implementation
  598. def response
  599. ret = {}
  600. resultstation = $db.execute "SELECT * FROM assignments"
  601. resultstation.each do |row|
  602. ret[row[0]] = row[1]
  603. end
  604. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  605. end
  606. end
  607. class SaveNewAssignment < Riddl::Implementation
  608. def response
  609. form = JSON.parse(@p[0].value.read);
  610. result = $db.execute "SELECT MAX(ID) FROM assignments"
  611. if(result[0][0] == nil)
  612. id = 0
  613. else
  614. id = result[0][0] +1
  615. end
  616. #bring given pattern into correct string (initially pattern could be in different order than required)
  617. pattern = [];
  618. fullcode = JSON.parse( File.read(File.join(File.dirname(__dir__),"server/json/ProductCode.json")))
  619. fullcode["pattern"].each do |child|
  620. pattern.push(form["parts"][child["abk"]])
  621. end
  622. checkimage = $db.execute "SELECT * FROM assignments WHERE image = '#{form["img"]}'"
  623. #if image not stored create new assignment with pattern, otherwise only add pattern
  624. if(checkimage[0] == nil)
  625. $db.execute("INSERT INTO assignments (ID, image) VALUES (?,?)", [id, form["img"]])
  626. form["parts"].each{ |key,val|
  627. $db.execute("INSERT INTO patternassignments (ID, AssID, type, value) VALUES (?,?,?,?)", [id, 0, key, val])
  628. }
  629. $db.execute("INSERT INTO patternassignments (ID, AssID, type, value) VALUES (?,?,?,?)", [id, 0, "STATION", form["station"]])
  630. $db.execute("INSERT INTO patternassignments (ID, AssID, type, value) VALUES (?,?,?,?)", [id, 0, "TEXT", form["assignmentText"]])
  631. ret = {:id => id}
  632. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  633. else
  634. maxID = $db.execute "SELECT MAX(AssID) FROM patternassignments WHERE ID ='#{checkimage[0][0]}'"
  635. if(maxID[0][0] == nil)
  636. maxID = 0
  637. else
  638. maxID = maxID[0][0] +1
  639. end
  640. #Search 4 assignment if none found add assignment
  641. #pp ListAssignmentSearch::prepare(@a[0][:appconf]["wasurl"], pattern.join('.'), form["station"], form["assignmentText"])
  642. if (!ListAssignmentSearch::prepare(@a[0][:appconf]["wasurl"], pattern.join('.'), form["station"], form["assignmentText"]).any?)
  643. form["parts"].each{ |key,val|
  644. $db.execute("INSERT INTO patternassignments (ID, AssID, type, value) VALUES (?,?,?,?)", [checkimage[0][0], maxID, key, val])
  645. }
  646. $db.execute("INSERT INTO patternassignments (ID, AssID, type, value) VALUES (?,?,?,?)", [checkimage[0][0], maxID, "STATION", form["station"]])
  647. $db.execute("INSERT INTO patternassignments (ID, AssID, type, value) VALUES (?,?,?,?)", [checkimage[0][0], maxID, "TEXT", form["assignmentText"]])
  648. ret = {:id => checkimage[0][0]}
  649. end
  650. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  651. end
  652. end
  653. end
  654. class GetAssignment < Riddl::Implementation
  655. def response
  656. ret = {}
  657. allAssIds = $db.execute "SELECT DISTINCT AssID FROM patternassignments WHERE ID = #{@r[1]}"
  658. allAssIds.each do |row|
  659. station = $db.execute "SELECT value FROM patternassignments WHERE ID = #{@r[1]} AND AssID = #{row[0]} AND type == 'STATION'"
  660. stationvalue = Integer(station[0][0])
  661. #old where pattern is stored as string
  662. #singleItem = $db.execute "SELECT value FROM patternassignments WHERE ID = #{@r[1]} AND AssID = #{row[0]} AND type != 'STATION'"
  663. #if(ret[stationvalue] == nil)
  664. # ret[stationvalue] = Hash.new()
  665. #end
  666. #ret[stationvalue][row[0]] = singleItem.join('.')
  667. singleItem = $db.execute "SELECT type, value FROM patternassignments WHERE ID = #{@r[1]} AND AssID = #{row[0]} AND type != 'STATION'"
  668. if(ret[stationvalue] == nil)
  669. ret[stationvalue] = Hash.new()
  670. end
  671. ret[stationvalue][row[0]] = Hash.new()
  672. singleItem.each do |it|
  673. ret[stationvalue][row[0]][it[0]] = it[1]
  674. end
  675. end
  676. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  677. end
  678. end
  679. class RenameAssignmentImagePath < Riddl::Implementation
  680. def response
  681. $db.execute("UPDATE assignments SET image = '#{JSON.parse(@p[0].value.read)["url"]}' WHERE ID = #{@r[1]}")
  682. end
  683. end
  684. class DeleteAssignment < Riddl::Implementation
  685. def response
  686. $db.execute("DELETE FROM assignments WHERE ID = ?", [@r[1]])
  687. end
  688. end
  689. class DeleteSingleAssignment < Riddl::Implementation
  690. def response
  691. $db.execute("DELETE FROM patternassignments WHERE AssID = ? AND ID = ?", [@r[2], @r[1]])
  692. end
  693. end
  694. class ListAssignmentSearch < Riddl::Implementation
  695. def self::prepare(appconf, pat, pat_station, pat_value)
  696. #https://centurio.work/customers/evva/was/ui/TransformProductCode.php?ProductCode=E.A.PZ.DZ-S.31.31.MP.SEP
  697. pattern = JSON.parse(Net::HTTP.get URI(appconf + "ui/TransformProductCode.php?ProductCode=" + pat))
  698. #remove empty entries from pattern
  699. pattern.each do |key, value|
  700. if(value == "")
  701. if(key == "Zi")
  702. elsif (key == "Kf")
  703. else
  704. pattern.delete(key)
  705. end
  706. end
  707. end
  708. emptypatternparts = []
  709. #fullcode = JSON.parse( File.read(File.join("json" , "ProductCode.json")))
  710. puts File.join(File.dirname(__dir__),"server/json/ProductCode.json")
  711. fullcode = JSON.parse( File.read(File.join(File.dirname(__dir__),"server/json/ProductCode.json")))
  712. fullcode["pattern"].each do |key|
  713. if(!pattern.has_key?(key["abk"]) )
  714. emptypatternparts.push(key["abk"])
  715. end
  716. end
  717. #$db.execute "CREATE TABLE IF NOT EXISTS patternassignments(ID INT, AssID INT, type CHARACTER(20), value CHARACTER(20), FOREIGN KEY(ID) REFERENCES assignments(ID) ON DELETE CASCADE)"
  718. #Get first key dynamicly and then build sql query
  719. if(pattern.keys[0] != nil)
  720. searchstring = "SELECT " + pattern.keys[0] + ".ID AS ID"
  721. searchstring = searchstring + " FROM " + pattern.map{ |key, val| "patternassignments " + key}.join(', ')
  722. searchstring = searchstring + ", " + emptypatternparts.map{ |key| "patternassignments " + key}.join(', ')
  723. searchstring = searchstring + " , patternassignments STATION , patternassignments ValText"
  724. searchstring = searchstring + " WHERE " + pattern.map{ |key, val| pattern.keys[0] + ".AssID == " + key + ".AssID"}.join(' AND ');
  725. searchstring = searchstring + " AND " + pattern.map{ |key, val| pattern.keys[0] + ".ID == " + key + ".ID"}.join(' AND ')
  726. searchstring = searchstring + " AND " + emptypatternparts.map{ |key| pattern.keys[0] + ".AssID == " + key + ".AssID"}.join(' AND ')
  727. searchstring = searchstring + " AND " + emptypatternparts.map{ |key| pattern.keys[0] + ".ID == " + key + ".ID"}.join(' AND ')
  728. searchstring = searchstring + " AND " + emptypatternparts.map{ |key| key + ".type == '" + key + "' AND " + key + ".value == ''" }.join(' AND ')
  729. searchstring = searchstring + " AND " + pattern.keys[0] + ".AssID == STATION.AssID"
  730. searchstring = searchstring + " AND " + pattern.keys[0] + ".AssID == ValText.AssID"
  731. searchstring = searchstring + " AND " + pattern.keys[0] + ".ID == STATION.ID"
  732. searchstring = searchstring + " AND " + pattern.keys[0] + ".ID == ValText.ID"
  733. searchstring = searchstring + " AND STATION.type == 'STATION'" + " AND STATION.value == '" + pat_station + "'"
  734. searchstring = searchstring + " AND ValText.type == 'TEXT'" + " AND ValText.value == '" + pat_value + "'"
  735. searchstring = searchstring + " AND " + pattern.map{ |key, val|
  736. #In case a value has the option "KeineAngabe" empty values are allowed
  737. if(val.start_with?("KeineAngabe"))
  738. key + ".type == '" + key + "' AND (" + key + ".value == '"+ val +"' or " + key + ".value == '*' or " + key + ".value == '')"
  739. else
  740. key + ".type == '" + key + "' AND (" + key + ".value == '"+ val +"' or " + key + ".value == '*')"
  741. end
  742. }.join(' AND ') + " ORDER BY ID ASC"
  743. #puts searchstring;
  744. else
  745. searchstring = "SELECT * FROM "
  746. searchstring = searchstring + "patternassignments STATION , patternassignments ValText"
  747. searchstring = searchstring + " WHERE"
  748. searchstring = searchstring + " STATION.type == 'STATION'" + " AND STATION.value == '" + pat_station + "'"
  749. searchstring = searchstring + " AND ValText.type == 'TEXT'" + " AND ValText.value == '" + pat_value + "'"
  750. searchstring = searchstring + " AND ValText.AssID == STATION.AssID"
  751. searchstring = searchstring + " ORDER BY ID ASC"
  752. end
  753. result = $db.execute searchstring;
  754. #Search for images with one or multiple found patternIDs
  755. ret = []
  756. if result.length > 0
  757. result.each do |item|
  758. result2 = $db.execute "SELECT DISTINCT image FROM assignments WHERE ID = #{item[0]}"
  759. result2.each do |item2|
  760. ret << item2[0]
  761. end
  762. end
  763. end
  764. return ret
  765. end
  766. def response
  767. ret = ListAssignmentSearch::prepare(@a[0][:appconf]["wasurl"], @p[0].value, @p[1].value, @p[2].value)
  768. Riddl::Parameter::Complex.new('list','application/json',JSON::pretty_generate(ret))
  769. end
  770. end
  771. def createDB(opts)
  772. $db.execute("PRAGMA foreign_keys=ON");
  773. $db.execute "CREATE TABLE IF NOT EXISTS stations(station INT, name VARCHAR(20), PRIMARY KEY(station))"
  774. opts[:appconf]["stations"].each { |n|
  775. CreateStation::createDB(n)
  776. }
  777. #vor DB struktur umstellung
  778. #$db.execute "CREATE TABLE IF NOT EXISTS station(station INT, patternID INT, pattern CHARACTER(256), description TEXT, date TEXT, P0 VARCHAR(10), P1 VARCHAR(10), P2 VARCHAR(10), P3 VARCHAR(10), P4 VARCHAR(10), P5 VARCHAR(10), P6 VARCHAR(10), P7 VARCHAR(10), P8 VARCHAR(10), P9 VARCHAR(10), P10 VARCHAR(10), PRIMARY KEY(station,patternID), UNIQUE(station, patternID))"
  779. #$db.execute "CREATE TABLE IF NOT EXISTS error(station INT, patternID INT, error TEXT, FOREIGN KEY(station, patternID) REFERENCES station(station, patternID) ON DELETE CASCADE)"
  780. #$db.execute "CREATE TABLE IF NOT EXISTS replacements(station INT, patternID INT, abbreviation TEXT, url TEXT, ordering INT, FOREIGN KEY(station, patternID) REFERENCES station(station, patternID) ON DELETE CASCADE)"
  781. #$db.execute "CREATE TABLE IF NOT EXISTS image(station INT, patternID INT, imageID INT, language CHARACTER(20), label TEXT, FOREIGN KEY(station, patternID) REFERENCES station(station, patternID) ON DELETE CASCADE,PRIMARY KEY(station,patternID,imageID,language))"
  782. $db.execute "CREATE TABLE IF NOT EXISTS stationpattern(station INT, internalID INT, description TEXT, date TEXT, PRIMARY KEY(internalID), UNIQUE(internalID))"
  783. $db.execute "CREATE TABLE IF NOT EXISTS pattern(internalID INT, type CHARACTER(20), value CHARACTER(20), FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  784. $db.execute "CREATE TABLE IF NOT EXISTS error(internalID INT, error TEXT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  785. $db.execute "CREATE TABLE IF NOT EXISTS replacements(internalID INT, abbreviation TEXT, url TEXT, ordering INT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  786. $db.execute "CREATE TABLE IF NOT EXISTS image(internalID INT, imageID INT, language CHARACTER(20), label TEXT, FOREIGN KEY(internalID) REFERENCES stationpattern(internalID) ON DELETE CASCADE)"
  787. $db.execute "CREATE TABLE IF NOT EXISTS assignments(ID INT, image TEXT, PRIMARY KEY(ID) UNIQUE (ID))"
  788. $db.execute "CREATE TABLE IF NOT EXISTS patternassignments(ID INT, AssID INT, type CHARACTER(20), value CHARACTER(20), FOREIGN KEY(ID) REFERENCES assignments(ID) ON DELETE CASCADE)"
  789. end
  790. server = Riddl::Server.new(File.join(__dir__,'/was.xml'), :host => 'localhost') do |opts|
  791. accessible_description true
  792. cross_site_xhr true
  793. createDB(opts)
  794. # opts[:appconf]
  795. on resource do
  796. run GetStations if get
  797. run CreateStation if post
  798. on resource 'cutimage' do
  799. run CutImage if get
  800. #should add deleteReplacement
  801. end
  802. on resource 'json' do
  803. run GetJsonFiles if get
  804. on resource '.*' do
  805. run SaveJson if put 'list'
  806. run GetJson if get
  807. end
  808. #should add deleteReplacement
  809. end
  810. on resource '\d+' do
  811. run GetStation if get
  812. run CreatePattern if post 'pattern'
  813. on resource '\d+' do
  814. run GetPattern if get
  815. run UpdatePattern if put 'pattern'
  816. run DeletePattern if delete
  817. run DuplicatePattern if put 'patternID'
  818. on resource 'error' do
  819. run SaveError if put 'error'
  820. run GetError if get
  821. #should add deleteerror
  822. end
  823. on resource 'replacement' do
  824. run SaveReplacement if put 'replacement'
  825. run GetReplacement if get
  826. #should add deleteReplacement
  827. end
  828. on resource 'images' do
  829. run GetImages, opts if get
  830. #run CreateImage if post #'image'
  831. run AddExternalImage if post 'externalImage'
  832. run UploadImage if post
  833. on resource 'reorder' do
  834. on resource do
  835. run ReorderImages if put 'orderlist'
  836. end
  837. end
  838. on resource '\d+' do
  839. run GetImage, opts if get
  840. on resource do
  841. run UpdateImageLabel if put 'label'
  842. run GetRealImage if get
  843. run DeleteImage if delete
  844. end
  845. end
  846. end
  847. end
  848. on resource 'search' do
  849. run ListSearch if get
  850. on resource 'imagesWIZ' do
  851. run SearchImages, opts if get
  852. on resource '\d+' do
  853. run SearchImagesSingle, opts if get
  854. end
  855. end
  856. on resource 'errorsWIZ' do
  857. run SearchErrors, opts if get
  858. end
  859. end
  860. end
  861. on resource 'assignments' do
  862. run GetAssignments if get
  863. run SaveNewAssignment, opts if post 'list'
  864. on resource 'search' do
  865. run ListAssignmentSearch, opts if get
  866. end
  867. on resource '\d+' do
  868. run GetAssignment if get
  869. run RenameAssignmentImagePath if put 'list'
  870. run DeleteAssignment if delete
  871. on resource '\d+' do
  872. run DeleteSingleAssignment if delete
  873. end
  874. end
  875. end
  876. end
  877. end.loop!