uAPI 11.4 KB
Newer Older
Danny SMc's avatar
Danny SMc committed
1 2
-- Written by DannySMc
-- Twitter: @dannysmc95
3
version = 2.1
Danny SMc's avatar
Danny SMc committed
4 5

function getVer()
Danny SMc's avatar
Danny SMc committed
6
	return version
Danny SMc's avatar
Danny SMc committed
7
end
Danny SMc's avatar
Danny SMc committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

-- Configuration File Protocols
function saveConfig(table, file)
  fConfig = fs.open(file, "w") or error("Cannot open file "..file, 2)
  fConfig.write(textutils.serialize(table))
  fConfig.close()
end

function loadConfig(file)
  fConfig = fs.open(file, "r")
  ret = textutils.unserialize(fConfig.readAll())
  return ret
end

-- Beaming Technology
function beam(username, xcord, ycord, zcord, blockSide)
	command = peripheral.wrap(blockSide)
	if command == "true" then
		command.setCommand("/tp "..username.." "..xcord.." "..ycord.." "..zcord)
		check = command.runCommand()
		if check == "true" then
			return true
		else
			return false
		end
	else
		return "Syntax Error"
	end
end

-- XP Functions
function xpGive(player, amount, blockSide)
	if player and amount and blockSide then
		command = peripheral.wrap(blockSide)
		command.setCommand("/xp "..amount.." "..player)
		check = command.runCommand()
		if check == "true" then
			return true
		else
			return false
		end
	else
		return false
	end
	if not player then
		return "Need player"
	end
	if not amount then
		return "Need amount"
	end
	if not blockSide then
		return "Need side of command block"
	end
end

-- Peripheral Functions
function findPeripheral(Perihp) --Returns side of first matching peripheral matching passed string  
  for _,s in ipairs(rs.getSides()) do
    if peripheral.isPresent(s) and peripheral.getType(s) == Perihp then
      return s   
    end
  end
  return false
end

-- Common Draw Functions
function cs()
	term.clear()
	term.setCursorPos(1,1)
	return
end

function setCol(textColour, backgroundColour)
	if textColour and backgroundColour then
		if term.isColour() then
			term.setTextColour(colours[textColour])
			term.setBackgroundColour(colours[backgroundColour])
			return true
		else
			return false
		end
	else
		return false
	end
end
 
 function resetCol()
	if term.isColour then
		term.setTextColour(colours.white)
		term.setBackgroundColour(colours.black)
		return true
	else
		return false
	end
end

-- Print Functions
function printC(Text, Line, NextLine, Color, BkgColor) -- print centered
  local x, y = term.getSize()
  x = x/2 - #Text/2
  term.setCursorPos(x, Line)
  if Color then setCol(Color, BkgColor) end
  term.write(Text) 
  if NextLine then
    term.setCursorPos(1, NextLine) 
  end
  if Color then resetCol(Color, BkgColor) end
  return true  
end

function printL(Text, Line, NextLine, Color, BkgColor) -- print line
Danny SMc's avatar
Danny SMc committed
119 120


Danny SMc's avatar
Danny SMc committed
121 122 123 124 125 126 127 128 129 130 131 132 133
  local x, y = term.getSize()
  if ((term.isColor) and (term.isColor() == false) and (Text == " ")) then Text = "-" end
  for i = 1, x do
    term.setCursorPos(i, Line)
    if Color then setCol(Color, BkgColor) end
    term.write(Text)
  end
  if NextLine then  
    term.setCursorPos(1, NextLine) 
  end
  if Color then resetCol(Color, BkgColor) end
  return true  
end
Danny SMc's avatar
Danny SMc committed
134

Danny SMc's avatar
Danny SMc committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
function printA(Text, xx, yy, NextLine, Color, BkgColor) -- print anywhere
  term.setCursorPos(xx,yy)
  if Color then setCol(Color, BkgColor) end
  term.write(Text)
  if NextLine then  
    term.setCursorPos(1, NextLine) 
  end
  if Color then resetCol(Color, BkgColor) end
  return true  
end

function clearLine(Line, NextLine) -- May seem a bit odd, but it may be usefull sometimes
  local x, y = term.getSize()
  for i = 1, x do
    term.setCursorPos(i, Line)
    term.write(" ")
  end  
  if not NextLine then  
    x, y = term.getCursorPos()
    term.setCursorPos(1, y+1) 
  end
  return true  
end

function drawBox(StartX, lengthX, StartY, lengthY, Text, Color, BkgColor) -- does what is says on the tin.
  local x, y = term.getSize()
  if Color then setCol(Color, BkgColor) end
  if not Text then Text = "*" end
  lengthX = lengthX - 1 
  lengthY = lengthY - 1
  EndX = StartX + lengthX  
  EndY = StartY + lengthY
  term.setCursorPos(StartX, StartY)
  term.write(string.rep(Text, lengthX))
  term.setCursorPos(StartX, EndY)
  term.write(string.rep(Text, lengthX)) 
  for i = StartY, EndY do
    term.setCursorPos(StartX, i)
    term.write(Text)
    term.setCursorPos(EndX, i)    
    term.write(Text)
  end
  resetCol(Color, BkgColor)
  return true  
end
 
 -- Download Functions
function getPBFile(PBCode, uPath) -- pastebin code of the file, and path to save
	local PBFile = http.get("http://pastebin.com/raw.php?i="..textutils.urlEncode(PBCode))
	if PBFile then
		local PBfileToWrite = PBfile.readAll()
		PBfile.close()

		local file = fs.open( uPath, "w" )
		file.write(PBfileToWrite)
		file.close()
			return true
		else
			return false
		end
end

-- Database Functions
db = {}
db.__index = db

function db.delete(Filename)
  if fs.exists(Filename) then
    fs.delete(Filename)
    return true
  end
  return false
end

function db.load(Filename) 
  if not fs.exists(Filename) then
    local F = fs.open(Filename, "w")
    F.write("{}")
    F.close()
  end
  local F = fs.open(Filename, "r")
  local Data = F.readAll()
  F.close()
  Data = textutils.unserialize(Data)
  return Data
end

function db.save(Filename, ATable) 
  local Data = textutils.serialize(ATable)
  local F = fs.open(Filename, "w")
  F.write(Data)
  F.close()
  return true
end

function db.search(searchstring, ATable)
  for i, V in pairs(ATable) do
    if tostring(ATable[i]) == tostring(searchstring) then
      return i
    end
  end 
  return 0
end

function db.removeString(Filename, AString)
  local TempT = db.load(Filename)
  if type(TempT) ~= "table" then return false end
  local Pos = db.search(AString, TempT)
  if Pos > 0 then
    table.remove(TempT, Pos)
    db.save(Filename, TempT)
    return true
  else
    return false
  end
end

function db.insertString(Filename, AString)
  local TempT = db.load(Filename)
  if type(TempT) ~= "table" then TempT = {} end
  table.insert(TempT, AString)
  db.save(Filename, TempT)
  return true
end

-- Serial Generator
function serialGen(digits) -- seems to become unstable above 18 digits long
Danny SMc's avatar
Danny SMc committed
262

Danny SMc's avatar
Danny SMc committed
263 264 265 266 267 268 269 270 271 272 273
  local serial
  for i = 1, digits do
    if i == 1 then
      serial = math.random(9)
    else
      serial = serial.. math.random(9)
    end
  end
  serial = tonumber(serial)
  return serial
end
Danny SMc's avatar
Danny SMc committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

-- Encryption & Checksum!
local function zfill(N)
	N=string.format("%X",N)
	Zs=""
	if #N==1 then
		Zs="0"
	end
	return Zs..N
end

local function serializeImpl(t)	
	local sType = type(t)
	if sType == "table" then
		local lstcnt=0
		for k,v in pairs(t) do
			lstcnt = lstcnt + 1
		end
		local result = "{"
		local aset=1
		for k,v in pairs(t) do
			if k==aset then
				result = result..serializeImpl(v)..","
				aset=aset+1
			else
				result = result..("["..serializeImpl(k).."]="..serializeImpl(v)..",")
			end
		end
		result = result.."}"
		return result
	elseif sType == "string" then
		return string.format("%q",t)
	elseif sType == "number" or sType == "boolean" or sType == "nil" then
		return tostring(t)
	elseif sType == "function" then
		local status,data=pcall(string.dump,t)
		if status then
			return 'func('..string.format("%q",data)..')'
		else
			error()
		end
	else
		error()
	end
end

local function split(T,func)
	if func then
		T=func(T)
	end
	local Out={}
	if type(T)=="table" then
		for k,v in pairs(T) do
			Out[split(k)]=split(v)
		end
	else
		Out=T
	end
	return Out
end

local function serialize( t )
	t=split(t)
	return serializeImpl( t, tTracking )
end

local function unserialize( s )
	local func, e = loadstring( "return "..s, "serialize" )
	local funcs={}
	if not func then
		return e
	end
	setfenv( func, {
		func=function(S)
			local new={}
			funcs[new]=S
			return new
		end,
	})
	return split(func(),function(val)
		if funcs[val] then
			return loadstring(funcs[val])
		else
			return val
		end
	end)
end

local function sure(N,n)
	if (l2-n)<1 then N="0" end
	return N
end

local function splitnum(S)
	Out=""
	for l1=1,#S,2 do
		l2=(#S-l1)+1
		CNum=tonumber("0x"..sure(string.sub(S,l2-1,l2-1),1) .. sure(string.sub(S,l2,l2),0))
		Out=string.char(CNum)..Out
	end
	return Out
end

local function wrap(N)
	return N-(math.floor(N/256)*256)
end

function checksum(S,num) -- args strInput and intPassNumber
	local sum=0
	for char in string.gmatch(S,".") do
		for l1=1,(num or 1) do
			math.randomseed(string.byte(char)+sum)
			sum=sum+math.random(0,9999)
		end
	end
	math.randomseed(sum)
	return sum
end

local function genkey(len,psw)
	checksum(psw)
	local key={}
	local tKeys={}
	for l1=1,len do
		local num=math.random(1,len)
		while tKeys[num] do
			num=math.random(1,len)
		end
		tKeys[num]=true
		key[l1]={num,math.random(0,255)}
	end
	return key
end

function encrypt(data,psw) -- args strInput and strPassword
	data=serialize(data)
	local chs=checksum(data)
	local key=genkey(#data,psw)
	local out={}
	local cnt=1
	for char in string.gmatch(data,".") do
		table.insert(out,key[cnt][1],zfill(wrap(string.byte(char)+key[cnt][2])),chars)
		cnt=cnt+1
	end
	return string.sub(serialize({chs,table.concat(out)}),2,-3)
end

function decrypt(data,psw) -- args strInput and strPassword
	local oData=data
	data=unserialize("{"..data.."}")
	if type(data)~="table" then
		return oData
	end
	local chs=data[1]
	data=data[2]
	local key=genkey((#data)/2,psw)
	local sKey={}
	for k,v in pairs(key) do
		sKey[v[1]]={k,v[2]}
	end
	local str=splitnum(data)
	local cnt=1
	local out={}
	for char in string.gmatch(str,".") do
		table.insert(out,sKey[cnt][1],string.char(wrap(string.byte(char)-sKey[cnt][2])))
		cnt=cnt+1
	end
	out=table.concat(out)
	if checksum(out or "")==chs then
		return unserialize(out)
	end
	return oData,out,chs
end

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
-- Checks for uAPI update!
function checkUpdate()
  if http then
    local getGit = http.get("https://raw.github.com/dannysmc95/uprograms/master/uVersions")
    local getGit = getGit.readAll()
    NVersion = textutils.unserialize(getGit)
    if NVersion["uapi"].Version > version then
      getGit = http.get(NVersion["uapi"].GitURL)
      getGit = getGit.readAll()
      local file = fs.open("uapi", "w")
      file.write(getGit)
      file.close()
      return true
    end
  else
    return false
  end
end

-- File Compression
local function readFile(filename)
  local contents = {}
  if fs.exists(filename) then
    local file = fs.open(filename, "r")
    while true do
      line = file.readLine()
      if line then
        table.insert(contents, line)
      else
        file.close()
        contents.filename = fs.getName(filename)
        return contents
      end
    end
  else
    error("File doesn't exist.")
  end
end

local function prepFiles(dir)
  if fs.exists(dir) and fs.isDir(dir) then
    local files = fs.list(dir)
    local contents = {}
    contents.bunch = true
    for _,name in pairs(files) do
      if fs.isDir(name) == false then
        contents[name] = readFile(dir..name)
      end
    end
    return contents
  else
    error("Not a directory.")
  end
end

function unpackFiles(m, dir)
  if (fs.exists(dir) == false) and (fs.isDir(dir) == false) then
    error("Passed dir is not a dir or doesn't exist")
  end
  if type(m) == "table" then
    if m.bunch then
      for name,data in pairs(m) do
        if type(data) == "table" then
          file = fs.open(dir.. data.filename, "w")
          for i = 1, #data do
            file.writeLine(data[i])
          end
          file.close()
        end
      end
    else
      file = fs.open(dir.. m.filename, "w")
      for i = 1, #m do
        file.writeLine(m[i])
      end
      file.close()
    end
  else
    error("Not a table.")
  end
end

function unpackFile(message, dir)
  unpackFiles(message, dir)
end

function packFile(filename)
  local file = readFile(filename)
  return file
end

function packDir(dir)
  local filer = prepFiles(dir)
  return filer
end