Skip to content

Instantly share code, notes, and snippets.

@SkyTheCoder
Created August 21, 2013 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SkyTheCoder/6297331 to your computer and use it in GitHub Desktop.
Save SkyTheCoder/6297331 to your computer and use it in GitHub Desktop.
Chat Room Release v0.0.34 -Chat!
Chat Room Tab Order Version: 0.0.34
------------------------------
This file should not be included in the Codea project.
#ChangeLog
#Main
#Log
#Server
--[[
0.0.34:
* Re-upload because nobody seemed to be able to get the last update
0.0.33:
+ Timestamps on messages! Now you know if they left a few minutes or hours ago
0.0.32:
+ A little beep sounds when there's an unread message on the Forums
* Easier to drag the chat text a little bit and not have "motion" when releasing
* Chat text "motion" pauses while you're dragging
0.0.31:
+ "New messages!" appears below the Forums button when the project detects unread comments or discussions
0.0.30:
* Shadows are always at full length and prettiness
* Chat view distance increased to 1000
* Fixed a bug where chat scroll lengths would be inaccurately measured, causing some text at the top to be clipped.
0.0.29:
* Fix for the previous fix for $DEVICE not working right not working right
0.0.28:
* Fix for new users crashing
0.0.27:
+ 'Splosion time for BG
+ Ping 'n' pong
0.0.26:
+ If someone tags someone you're following it will alert you, too, so you don't only hear half of the conversation
+ The orientation with be locked on a landscape mode so the below feature works properly without flipping upside-down
* Text shadows will now fall with gravity on a device where the gyroscope is available
* Using /alert <message> will now show the native iOS alert box
* $DEVICE now works properly on an iPad 4
0.0.25:
+ Pretty text shadows
0.0.24:
+ Project finally shared with the Codea forums!
+ Commented-out fail of the BG's theme song
* Minor tweak to the "left the chat room" message
0.0.23:
+ /rename brings up the name choosing GUI, if you want a new name
* Much smoother chat scrolling
0.0.22:
* Fixed a bug where chat would scroll when you presssed a button
0.0.21:
* Re-upload
0.0.20:
+ Use &^ and it turns it to $, useful for demonstrating things such as $RANK without it being changed
+ Use ?:/ and it turns to /, useful for demonstrating commands such as /help
+ $DEVICE will change to whatever device you're using, and its version.
+ Chat history cache increased to 100 messages
+ Drag with your finger to scroll through chat
+ Close button
+ Forums button
+ FULLSCREEN_NO_BUTTONS display mode
0.0.19:
+ BG tail
+ BG has an animated and colored BG
+ BG stretches and wiggles up and down
0.0.18:
* Fixed a bug with /leave
0.0.17:
+ BG tweening
0.0.16:
+ /help displays a list of commands
0.0.15:
+ People you're following and hashtags you're following now save between sessions
+ /leave leaves the chat room and says so. WARNING: You MUST use this to leave if you wish to save the people you're following and the hashtags you're watching!
+ /unfollow unfollows someone
+ /unwatch stops watching a hashtag
0.0.14:
* Re-upload
0.0.13:
* Re-upload
0.0.12:
* Re-upload
* Fixed a minor bug that would cause the first text loaded to be in the wrong order.
0.0.11:
* Re-upload
0.0.10:
* Re-upload
0.0.9:
+ Chat history stored client-side
+ Changelog
0.0.8:
+ /watch <name> can follow a hashtag and alert you when someone uses #<name>
+ /follow <name> can follow a person and alert you when they say something.
* Finally fixed debugging info and chat formatting
0.0.7:
* Fixed even more formatting issues
0.0.6:
* Fixed formatting issues
0.0.5:
+ Chat lines reformatted
* More debugging stuff
0.0.4:
* Even more debugging stuff
0.0.3:
+ /say <message> speaks through the server
+ /alert <message> speaks with the prefix [ALERT]
* More debugging stuff
0.0.2:
* Re-upload
0.0.1:
+ Initial release
--]]
--[[
--This is your return data structure
description:
forks_url: https://api.github.com/gists/b09cd401cc606277e723/forks
comments: 0
git_push_url: https://gist.github.com/b09cd401cc606277e723.git
url: https://api.github.com/gists/b09cd401cc606277e723
comments_url: https://api.github.com/gists/b09cd401cc606277e723/comments
user:
followers_url: https://api.github.com/users/SkyTheCoder/followers
gists_url: https://api.github.com/users/SkyTheCoder/gists{/gist_id}
repos_url: https://api.github.com/users/SkyTheCoder/repos
gravatar_id: c63a6ce8510551f2af6ff27eb9938459
html_url: https://github.com/SkyTheCoder
events_url: https://api.github.com/users/SkyTheCoder/events{/privacy}
type: User
starred_url: https://api.github.com/users/SkyTheCoder/starred{/owner}{/repo}
received_events_url: https://api.github.com/users/SkyTheCoder/received_events
subscriptions_url: https://api.github.com/users/SkyTheCoder/subscriptions
avatar_url: https://secure.gravatar.com/avatar/c63a6ce8510551f2af6ff27eb9938459?d=https://a248.e.akamai.net/assets.github.com/images/gravatars/gravatar-user-420.png
organizations_url: https://api.github.com/users/SkyTheCoder/orgs
following_url: https://api.github.com/users/SkyTheCoder/following{/other_user}
url: https://api.github.com/users/SkyTheCoder
login: SkyTheCoder
id: 4.61453e+06
id: b09cd401cc606277e723
created_at: 2013-07-13T00:01:24Z
git_pull_url: https://gist.github.com/b09cd401cc606277e723.git
updated_at: 2013-07-13T00:01:25Z
history:
1:
version: e916a36d1209d800443129bee8023a0a177f013b
user:
followers_url: https://api.github.com/users/SkyTheCoder/followers
gists_url: https://api.github.com/users/SkyTheCoder/gists{/gist_id}
repos_url: https://api.github.com/users/SkyTheCoder/repos
gravatar_id: c63a6ce8510551f2af6ff27eb9938459
html_url: https://github.com/SkyTheCoder
events_url: https://api.github.com/users/SkyTheCoder/events{/privacy}
type: User
starred_url: https://api.github.com/users/SkyTheCoder/starred{/owner}{/repo}
received_events_url: https://api.github.com/users/SkyTheCoder/received_events
subscriptions_url: https://api.github.com/users/SkyTheCoder/subscriptions
avatar_url: https://secure.gravatar.com/avatar/c63a6ce8510551f2af6ff27eb9938459?d=https://a248.e.akamai.net/assets.github.com/images/gravatars/gravatar-user-420.png
organizations_url: https://api.github.com/users/SkyTheCoder/orgs
following_url: https://api.github.com/users/SkyTheCoder/following{/other_user}
url: https://api.github.com/users/SkyTheCoder
login: SkyTheCoder
id: 4.61453e+06
url: https://api.github.com/gists/b09cd401cc606277e723/e916a36d1209d800443129bee8023a0a177f013b
change_status:
total: 1
deletions: 0
additions: 1
committed_at: 2013-07-13T00:01:24Z
public: false
files:
ChatRoomData:
type: text/plain
filename: ChatRoomData
raw_url: https://gist.github.com/raw/b09cd401cc606277e723/6a58ae501cbc684e1cefd5c5dbbaf8145050edc6/ChatRoomData
content: Does this message appear at the top of the chat room? Oh, well...
size: 65
commits_url: https://api.github.com/gists/b09cd401cc606277e723/commits
html_url: https://gist.github.com/b09cd401cc606277e723
forks:
--]]
-- Chat Room
PROJECTNAME = "Chat Room"
VERSION = "0.0.34"
if CurrentOrientation == LANDSCAPE_LEFT then
supportedOrientations(LANDSCAPE_LEFT)
elseif CurrentOrientation == LANDSCAPE_RIGHT then
supportedOrientations(LANDSCAPE_RIGHT)
else
supportedOrientations(LANDSCAPE_RIGHT)
end
-- Use this function to perform your initial setup
function setup()
VersionUpdateChecker.check()
math.randomseed(os.time())
displayMode(STANDARD)
str = ""
LSTRING = ""
bcolor = 0
kbuffer = ""
server = Server()
l = 0
t = 50
r = WIDTH
b = 0
viewDistance = 1000
prev = {}
for i = 1, viewDistance do
table.insert(prev, "")
end
bg = nil
http.request("http://cdn.scratch.mit.edu/get_image/gallery/225427_170x100.png?v=1372714856.91", get)
bgTail = nil
http.request("http://fc01.deviantart.net/fs70/f/2011/360/e/3/nyan_cat_s_rainbow_by_kkiittuuss-d4k5mgd.psd", got)
star = readImage("Space Art:Star")
fade = {x = 255, y = 255, size = 255}
bgTimer = 0
bgScreenDist = 800
bgPos = {x = -bgScreenDist, y = HEIGHT / 2}
closeDim = {w = 0, h = 0}
forumDim = {w = 0, h = 0}
offset = 0
mot = 0
len = 0
prevMot = {}
motClip = 10
lastTouchTime = 0
lastTouchPos = vec2(0, 0)
forumsOldNew = false
forumsNew = false
loopCF(1)
--sound(DATA, "ZgBAWABAQEBAQEBAAAAAAOUhlD0IlqM+UwBAf0BAQEBAQEBA")
--aNote = "ZgBAGwBAQEBAQEBAAAAAAOUhlD0IlqM+UwBAf0BAQEBAQEBA"
--bNote = "ZgBALQBAQEBAQEBAAAAAAOUhlD0IlqM+UwBAf0BAQEBAQEBA"
--cNote = "ZgBAQABAQEBAQEBAAAAAAOUhlD0IlqM+UwBAf0BAQEBAQEBA"
--dNote = "ZgBATABAQEBAQEBAAAAAAOUhlD0IlqM+UwBAf0BAQEBAQEBA"
--eNote = "ZgBAWABAQEBAQEBAAAAAAOUhlD0IlqM+UwBAf0BAQEBAQEBA"
end
function loopCF(time)
http.request("http://www.twolivesleft.com/Codea/Talk/discussions", analyze)
tween.delay(time, function() loopCF(time) end)
end
function analyze(html, status)
if status == 200 and html ~= nil then
if string.find(html, "Counts NewCounts") ~= nil then
forumsNew = true
else
forumsNew = false
end
end
end
function get(data, status)
if status == 200 and data ~= nil then
bg = data
end
end
function got(data, status)
if status == 200 and data ~= nil then
bgTail = data
end
end
function params()
parameter.clear()
displayMode(FULLSCREEN_NO_BUTTONS)
end
-- This function gets called once every frame
function draw()
if forumsNew and not forumsOldNew then
sound(SOUND_PICKUP, 17454)
forumsOldNew = true
end
if CurrentTouch.state == ENDED or CurrentTouch.state == CANCELLED then
mot = tonumber(string.format("%1.3f", mot * 0.947))
if math.abs(mot) <= 0.02 then
mot = 0
end
end
if #prevMot > motClip then
for i = #prevMot, motClip + 1, -1 do
table.remove(prevMot, i)
end
end
--print(offset)
if CurrentTouch.state == ENDED or CurrentTouch.state == CANCELLED then
offset = math.max(0, math.min(len - HEIGHT, offset - mot))
end
if offset == 0 or offset == len - HEIGHT then
mot = 0
end
--camera(WIDTH / 2, HEIGHT / 2, WIDTH - 100, WIDTH / 2, HEIGHT / 2, 0)
--perspective(45)
bgTimer = math.max(0, bgTimer - 1)
smooth()
background(fade.x, fade.y, fade.size, 255)
stroke(127)
strokeWidth(6)
if bgTimer >= 1 and bg ~= nil and bgTail ~= nil then
--notes = {"c", "d", "b", "c", "b", "c", "b", "a", "b", "c"}
--for k, v in ipairs(notes) do
--if 600 - bgTimer == k * 10 then
--sound(DATA, loadstring("return " .. v .. "Note")())
--end
--end
math.randomseed(math.floor(bgTimer / 15))
for i = 1, 25 do
tint(255, math.random() * 255)
sprite(star, math.random() * WIDTH, math.random() * HEIGHT, math.random() * 35)
noTint()
end
local m = 1
if not isEvenPositive(bgTimer / 30) then
m = -1
end
sprite(bgTail, bgPos.x - 150, bgPos.y, m * 200, 60)
sprite(bg, bgPos.x + (5 * -math.sin(bgTimer / 10)), bgPos.y + (5 * math.cos(bgTimer / 10)), 200 + (5 * -math.sin(bgTimer / 10)), 120)
end
fill(0)
font("Inconsolata")
textMode(CENTER)
fontSize(24)
textWrapWidth(WIDTH - 24)
if bcolor == 0 then
fill(0)
stroke(127)
else
--fill(127)
--stroke(63)
end
rectMode(CORNER)
textMode(CORNER)
if isKeyboardShowing() then
--rect(WIDTH / 2, (HEIGHT / 2) - 10, WIDTH, 50 + #buffer)
rect(0, (HEIGHT / 2) - 35, WIDTH, 50 + (#kbuffer / (WIDTH / 360)))
else
--rect(WIDTH / 2,25,WIDTH,50)
rect(0, 0, WIDTH, 50 + (#LSTRING / (WIDTH / 360)))
end
rectMode(CORNER)
--[[
if isKeyboardShowing() then
text(server.chatStr, 10, ((HEIGHT / 2) + 45) )
--print(server.chatStr)
else
text(server.chatStr, 10, 55)
end
--]]
local yOff = string.len(LSTRING) / (WIDTH / 360)
if isKeyboardShowing() then
yOff = string.len(kbuffer) / (WIDTH / 360)
end
--for i = #prev, #prev - (viewDistance - 1), -1 do
yOff = yOff - offset
len = 293
--len = 0
--len = len + (string.len("Type /help for commands") / (WIDTH / 360))
for i = 1, viewDistance do
if server.pOutput[i] ~= nil then
fill(127)
local w, h = textSize(server.pOutput[i]["message"])
local abcw, abch = textSize("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
len = len + math.max(h, abch)
len = len + abch / 6
len = len + (string.len(server.pOutput[i]["message"]) / (WIDTH / 360))
local gxOff = 1.5 * math.sin(math.pi / 2 + math.atan2(Gravity.y, Gravity.x))
local gyOff = -1.5 * math.cos(math.pi / 2 + math.atan2(Gravity.y, Gravity.x))
if isKeyboardShowing() then
--text(prev[i], 10, ((HEIGHT / 2) + 45) + (30 * (#prev - i)) + 24 + yOff)
text(server.pOutput[i]["message"], 10 + gxOff, ((HEIGHT / 2) + (36 * i) + yOff) + gyOff)
else
--text(prev[i], 10, 55 + (30 * (#prev - i)) + yOff)
text(server.pOutput[i]["message"], 10 + gxOff, (55 + (36 * i) + yOff) + gyOff)
end
fill(0)
if isKeyboardShowing() then
--text(prev[i], 10, ((HEIGHT / 2) + 45) + (30 * (#prev - i)) + 24 + yOff)
text(server.pOutput[i]["message"], 10, (HEIGHT / 2) + (36 * i) + yOff)
else
--text(prev[i], 10, 55 + (30 * (#prev - i)) + yOff)
text(server.pOutput[i]["message"], 10, 55 + (36 * i) + yOff)
end
yOff = yOff + (string.len(server.pOutput[i]["message"]) / (WIDTH / 360))
end
end
kbuffer = keyboardBuffer()
fill(255)
if isKeyboardShowing() then
if kbuffer ~= nil then
local l = ""
if math.floor(((math.sin(5*ElapsedTime)+1)*0.5)+0.5) < 0.5 and isKeyboardShowing() then
l = "|"
end
text(kbuffer .. l,10,(HEIGHT/2)-25)
end
else
bcolor = 0
text(LSTRING,10,10)
end
noStroke()
fill(fade.x, fade.y, fade.size, 255)
rect(0, HEIGHT - 93, WIDTH, 94)
rectMode(CENTER)
textMode(CENTER)
local gxOff = 1.5 * math.sin(math.pi / 2 + math.atan2(Gravity.y, Gravity.x))
local gyOff = -1.5 * math.cos(math.pi / 2 + math.atan2(Gravity.y, Gravity.x))
fill(127)
translate(gxOff, gyOff)
fontSize(36)
text("Chat Room",WIDTH/2,HEIGHT-25)
fontSize(24)
text("By SkyTheCoder (GUI & Idea) & Briarfox (Networking)",WIDTH/2,HEIGHT-50)
fontSize(14)
text(os.date(),WIDTH/2,HEIGHT-75)
fontSize(24)
local w , h = textSize("Close")
closeDim = {w = w, h = h}
text("Close", w / 2, HEIGHT - (h / 2))
w, h = textSize("Forums")
forumDim = {w = w, h = h}
text("Forums", WIDTH - (w / 2), HEIGHT - (h / 2))
translate(-gxOff, -gyOff)
fill(0)
fontSize(36)
text("Chat Room",WIDTH/2,HEIGHT-25)
fontSize(24)
text("By SkyTheCoder (GUI & Idea) & Briarfox (Networking)",WIDTH/2,HEIGHT-50)
fontSize(14)
text(os.date(),WIDTH/2,HEIGHT-75)
fontSize(24)
local w , h = textSize("Close")
closeDim = {w = w, h = h}
text("Close", w / 2, HEIGHT - (h / 2))
w, h = textSize("Forums")
forumDim = {w = w, h = h}
text("Forums", WIDTH - (w / 2), HEIGHT - (h / 2))
if forumsNew then
local nmw, nmh = textSize("New messages!")
text("New messages!", WIDTH - nmw / 2, HEIGHT - h / 2 - nmh / 2)
end
end
function touched(touch)
if touch.state == BEGAN then
if touch.x > l and touch.x < r and touch.y > b and touch.y < t then
showKeyboard()
bcolor = 1
elseif touch.x >= 0 and touch.y >= HEIGHT - closeDim.h and touch.x <= closeDim.w and touch.y <= HEIGHT then
server:sendChat("/leave")
elseif touch.x >= WIDTH - forumDim.w and touch.y >= HEIGHT - forumDim.h and touch.x <= WIDTH and touch.y <= HEIGHT then
openURL("http://www.twolivesleft.com/Codea/Talk/discussions", true)
close()
else
if isKeyboardShowing() then
hideKeyboard()
bcolor = 0
end
end
end
if touch.state == MOVING then
if touch.y > 50 + (#LSTRING / (WIDTH / 360)) and touch.y < HEIGHT - 94 then
table.insert(prevMot, touch.deltaY)
--print(touch.deltaY)
offset = offset - touch.deltaY
local tRange = 10
if math.abs(touch.x - lastTouchPos.x) > tRange and math.abs(touch.y - lastTouchPos.y) > tRange then
lastTouchTime = ElapsedTime
lastTouchPos = vec2(touch.x, touch.y)
end
end
end
if touch.state == ENDED or touch.state == CANCELLED then
if touch.y > 50 + (#LSTRING / (WIDTH / 360)) and touch.y < HEIGHT - 94 then
local m = 0
local c = 0
for i = 1, #prevMot do
m = m + prevMot[i]
c = c + 1
end
prevMot = {}
local a = multiplier(mot)
local b = multiplier(m / c)
if ElapsedTime - lastTouchTime <= 0.25 then
if a == b then
mot = mot + (m / c)
else
mot = m / c
end
end
end
end
end
function keyboard(key)
if key == BACKSPACE then
kbuffer = string.sub(kbuffer, 1, string.len(kbuffer) - 1)
end
if key == RETURN then
str = kbuffer
LSTRING = str
hideKeyboard()
--print(str)
server:sendChat(str)
--tPrint(str)
end
end
function tPrint(text)
table.insert(prev, tostring(text))
end
function string.replace(s, pattern, replacement)
return (s:gsub(pattern, replacement))
end
function replace(s, pattern, replacement)
local str = s
while string.find(str, pattern) ~= nil do
local pstart, pend = string.find(str, pattern)
str = string.sub(str, 1, pstart - 1) .. replacement .. string.sub(str, pend + 1, string.len(str))
end
return str
end
function string.remove(s, pattern)
return string.replace(s, pattern, "")
end
function string.startsWith(s, pattern)
return not (not s:find("^"..pattern))
end
function string.endsWith(s, pattern)
return not (not s:find(pattern .. "$"))
end
function string.split(s, pattern)
local t = {}
for w in s:gmatch("[^"..pattern.."]+") do
table.insert(t, w)
end
return t
end
function split(s, pattern)
local str = s
str = str .. pattern
local strTable = {}
while string.find(str, pattern) ~= nil do
local pstart, pend = string.find(str, pattern)
table.insert(strTable, string.sub(str, 1, pstart - 1))
str = string.sub(str, pend + 1, string.len(str))
end
return strTable
end
function string.allChars(s)
local t = {}
for c in s:gmatch(".") do
table.insert(t, c)
end
return t
end
function string.slice(s, interval)
t = {}
for sl in s:gmatch(string.rep(".", interval)) do
table.insert(t, sl)
end
return t
end
function multiplier(i)
if math.abs(i) == i then return 1 else return -1 end
end
function isEvenPositive(i)
local j = i
while j > 2 do
j = j - 2
end
return math.floor(j) == 2 or math.floor(j) == 0
end
-----------------------------
--Update Checker Code added by AutoGist
-----------------------------
VersionUpdateChecker = {}
VersionUpdateChecker.gistURL = "https://api.github.com/gists/6297331"
VersionUpdateChecker.check = function()
local jsonURL = "https://dl.dropboxusercontent.com/s/9e4nvqeu4hsux2q/Json.lua?token_hash=AAFyMB98j4bnt_1gawf9wSke52hsoC7hsIvARcTuZNeOEw&dl=1"
local jsonSuccess = function(data)
local jsonCode = data
if jsonCode then local l = loadstring(jsonCode) l() end
local handleSuccess = function(data)
local gist = json.decode(data)
local version = string.match(gist.description,"%d+%.%d+%.%d+")
if VERSION ~= version then
displayMode(STANDARD)
print("Click Update_Project.")
alert("New Update Availiable! Click Update.","Update")
parameter.action("Update_Project",function() VersionUpdateChecker.GetProject() end)
end
end
http.request(VersionUpdateChecker.gistURL,handleSuccess,function() print("Update Failed") end)
end
http.request(jsonURL,jsonSuccess,function() print("Check Internet Connection") end)
end
function VersionUpdateChecker.GetProject()
local handleSuccess = function(data,i,j)
if listProjectTabs(PROJECTNAME) == nil then
error("Check Project Name")
end
local gist = json.decode(data)
local projName = PROJECTNAME
if gist.files["1aTabOrder"] then
print("***Tab Order Found***")
local taborder = gist.files["1aTabOrder"].content
local strStart =1
local strEnd =0
strStart = string.find(taborder,"#",strEnd)
strEnd = string.find(taborder,"\n",strStart)
while strStart do
local tmp = string.sub(taborder,strStart+1,strEnd-1)
local name = PROJECTNAME..":"..tmp
tmp = tmp..".lua"
saveProjectTab(name,gist.files[tmp].content)
strStart = string.find(taborder,"#",strEnd)
strEnd = string.find(taborder,"\n",strStart)
end
else
for k,v in pairs(gist.files) do
local name = PROJECTNAME .. ":" .. string.gsub(k,".lua","")
saveProjectTab(name, v.content)
end
end
if gist.files["ChangeLog.lua"] then
local str = gist.files["ChangeLog.lua"].content
alert(str,"Version Notes")
end
sound(SOUND_PICKUP, 24058)
print("Reload Project to finish update!")
end
http.request(VersionUpdateChecker.gistURL,handleSuccess,function(data) print("Update Failed") end)
end
--End of Update Checker
--------------------------------------------------
Server = class()
function Server:init()
self.user = readLocalData("Chat_User")
if self.user == nil then
displayMode(STANDARD)
parameter.text("Username", "Enter your username here...")
parameter.action("Submit",function()
saveLocalData("Chat_User", Username)
self.user = Username
self:sendFormattedMessage("Guest has chosen the name $USERNAME!")
params()
end)
else
params()
end
self.rank = "User"
self.chatStr = ""
self.gottenChat = false
self.cache = {}
self.pMax = 0
self.pOutput = {{message = "(You can actually type @SkyTheCoder or @Briarfox in chat and they will see)"}, {message = "Please contact @SkyTheCoder or @Briarfox for additional help"}, {message = "Don't forget to use /leave to exit!"}, {message = "Type /help for commands"}}
local tags = readLocalData("Tags")
if tags ~= nil then
self.tags = split(tags, "|")
else
self.tags = {}
end
local followees = readLocalData("Followees")
if followees ~= nil then
self.followees = split(followees, "|")
else
self.followees = {}
end
self.host = "http://code.housercompany.com/"
self.send = "Chat_Send.php"
self.recieve = "Chat_Recieve.php"
self:getChat()
self:checkChat(1,function() self:getChat() end)
self:sendFormattedMessage("(" .. string.sub(os.date(), 12, 19) ..") [$RANK] $USERNAME has joined the chat room!")
end
function Server:getChat()
local fail = function(err)
tPrint(err)
end
http.request(self.host..self.recieve, function(d)
--output.clear()
--print(d)
self.chatStr = d
--tPrint(d)
--prev = string.split(d, "\n")
local output = {}
for ID, MESSAGE in string.gmatch(self.chatStr, "$ID(%d-)$START(.-)$END") do
table.insert(output, {id = ID, message = MESSAGE})
end
local max = 0
for i = #output, 1, -1 do
max = math.max(max, output[i]["id"])
end
for i = #output, 1, -1 do
local k = output[i]["id"]
local v = output[i]["message"]
if tonumber(k) > self.pMax then
table.insert(self.pOutput, 1, {id = k, message = v})
if string.find(v, " has summoned the Nyan Cat!", 1, true) ~= nil and self.gottenChat then
tween(2, fade, {x = 31, y = 44, size = 158}, tween.easing.linear, function()
bgTimer = 600
tween(10, bgPos, {x = WIDTH + bgScreenDist}, tween.easing.linear, function()
bgPos = {x = -bgScreenDist, y = HEIGHT / 2}
tween(2, fade, {x = 255, y = 255, size = 255}, tween.easing.linear, function()
math.randomseed(os.time())
end)
end)
end)
--print("Ding")
end
if (string.find(string.lower(v), "bang", 1, true) ~= nil or string.find(string.lower(v), "boom", 1, true) ~= nil) and self.gottenChat and bgTimer >= 1 then
tween(2, bgPos, {y = 90 + (#LSTRING / (WIDTH / 360))}, tween.easing.bounceOut)
end
if string.find(v, "[ALERT]", 1, true) == 1 and self.gottenChat then
alert(string.sub(v, 8, string.len(v)), "Codea Chat Room Alert")
end
for i, j in pairs(self.tags) do
if string.find(v, "#" .. j, 1, true) ~= nil and self.gottenChat then
sound(SOUND_PICKUP, 451)
end
end
for i, j in pairs(self.followees) do
if (string.find(v, "<" .. j .. ">", 1, true) ~= nil or string.find(v, "@" .. j, 1, true) ~= nil) and self.gottenChat then
sound(SOUND_PICKUP, 460)
end
end
if string.find(v, "@" .. self.user or "Guest", 1, true) ~= nil and self.gottenChat then
sound(SOUND_PICKUP, 20721)
end
end
end
--self.pOutput = output
self.pMax = max
self.gottenChat = true
end)
end
function Server:sendChat(str)
if str == "" then return end
local headers={}
headers["Accept"]="text/plain"
headers["Content-Type"]="application/x-www-form-urlencoded"
headers["Accept-Charset"]="utf-8"
local data = ""
local format = function(format, msg, cmd)
local device = deviceMetrics().platformName
if cmd ~= nil then
return string.gsub(string.gsub(string.gsub(string.gsub(string.gsub(string.gsub(format, "$MESSAGE", string.sub(msg, math.min(string.len(cmd) + 2, string.len(msg)),string.len(msg))), "$RANK", self.rank), "$USERNAME", (self.user or "Guest")), "$DEVICE", device), "&^", "$"), "?:/", "/")
else
return string.gsub(string.gsub(string.gsub(string.gsub(string.gsub(string.gsub(format, "$MESSAGE", msg), "$RANK", self.rank), "$USERNAME", (self.user or "Guest")), "$DEVICE", device), "&^", "$"), "?:/", "/")
end
end
if string.find(str, "/help", 1, true) == 1 then
table.insert(self.pOutput, 1, {message = "(Page 1 of 1) Help:"})
table.insert(self.pOutput, 1, {message = "/help - Shows this menu"})
table.insert(self.pOutput, 1, {message = "/leave - Leaves the chat room and saves what hashtags you're watching and who you're following"})
table.insert(self.pOutput, 1, {message = "/say <message> - Speaks with the prefix [Server]"})
table.insert(self.pOutput, 1, {message = "/alert <message> - Speaks with the prefix [ALERT]"})
table.insert(self.pOutput, 1, {message = "/rename - Brings up the name choosing GUI"})
table.insert(self.pOutput, 1, {message = "/watch <name> - Watches a hashtag"})
table.insert(self.pOutput, 1, {message = "/follow <name> - Follows a person"})
table.insert(self.pOutput, 1, {message = "/unwatch <name> - Stops watching a hashtag"})
table.insert(self.pOutput, 1, {message = "/unfollow <name> - Stops following a person"})
return
elseif string.find(str, "/ping", 1, true) == 1 then
table.insert(self.pOutput, 1, {message = "Pong!"})
return
elseif string.find(str, "/pong", 1, true) == 1 then
table.insert(self.pOutput, 1, {message = "Ping!"})
return
elseif string.find(str, "/say", 1, true) == 1 then -- /say
data = "message=" .. format("[Server] $MESSAGE", str, "/say")
elseif string.find(str, "/alert", 1, true) == 1 then -- /alert
data = "message=" .. format("[ALERT] $MESSAGE", str, "/alert")
elseif string.find(str, "/rename", 1, true) == 1 then -- /rename
data = "message=" .. format("$USERNAME is choosing a new name...", str, "/rename")
local oldName = format("$USERNAME", "", "")
displayMode(STANDARD)
parameter.text("Username", "Enter your username here...")
parameter.action("Submit",function()
saveLocalData("Chat_User", Username)
self.user = Username
self:sendFormattedMessage(oldName .. " has chosen the name $USERNAME!")
params()
end)
elseif string.find(str, "/watch", 1, true) == 1 then -- /watch
data = "message=" ..
format("$USERNAME is now watching the hashtag $MESSAGE!", str, "/watch")
self.tags[#self.tags + 1] = format("$MESSAGE", str, "/watch")
elseif string.find(str, "/follow", 1, true) == 1 then -- /follow
data = "message=" ..
format("$USERNAME is now following $MESSAGE!", str, "/follow")
self.followees[#self.followees + 1] = format("$MESSAGE", str, "/follow")
elseif string.find(str, "/unwatch", 1, true) == 1 then -- /unwatch
data = "message=" ..
format("$USERNAME is no longer watching the hashtag $MESSAGE!", str, "/unwatch")
for k, v in pairs(self.tags) do
if v == format("$MESSAGE", str, "/unwatch") then
table.remove(self.tags, k)
end
end
elseif string.find(str, "/unfollow", 1, true) == 1 then -- /unfollow
data = "message=" ..
format("$USERNAME is no longer following $MESSAGE!", str, "/unfollow")
for k, v in pairs(self.followees) do
if v == format("$MESSAGE", str, "/unfollow") then
table.remove(self.followees, k)
end
end
elseif string.find(str, "/leave", 1, true) == 1 then -- /leave
data = "message=" .. format("(" .. string.sub(os.date(), 12, 19) ..") [$RANK] $USERNAME has left the chat room!", str, "/leave")
local tags = ""
for k, v in pairs(self.tags) do
if tags == "" then tags = v else tags = tags .. "|" .. v end
end
local followees = ""
for k, v in pairs(self.followees) do
if followees == "" then followees = v else followees = followees .. "|" .. v end
end
if tags == "" then tags = nil end
if followees == "" then followees = nil end
saveLocalData("Tags", tags)
saveLocalData("Followees", followees)
elseif string.find(str, "/nyancat", 1, true) == 1 then -- /nyancat
data = "message=" .. format("$USERNAME has summoned the Nyan Cat!", str, "/nyancat")
--bgTimer = 600
else -- Plain
data = "message=" .. format("(" .. string.sub(os.date(), 12, 19) ..") [$RANK] <$USERNAME> $MESSAGE", str, nil)
end
http.request(self.host..self.send,
function(res)
--print(res)
end,
function(res)
-- print(res)
end,
{ method="POST", headers=headers, data=data }
)
if data == "message=" .. format("(" .. string.sub(os.date(), 12, 19) ..") [$RANK] $USERNAME has left the chat room!", str, "/leave") then
close()
end
end
function Server:sendPlainMessage(msg)
local headers={}
headers["Accept"]="text/plain"
headers["Content-Type"]="application/x-www-form-urlencoded"
headers["Accept-Charset"]="utf-8"
local data = "message=" .. msg
http.request(self.host..self.send,
function(res)
--print(res)
end,
function(res)
-- print(res)
end,
{ method="POST", headers=headers, data=data }
)
end
function Server:sendFormattedMessage(msg)
local format = function(msg)
local device = deviceMetrics().platformName
return string.gsub(string.gsub(string.gsub(string.gsub(string.gsub(msg, "$RANK", self.rank), "$USERNAME", (self.user or "Guest")), "$DEVICE", device), "&^", "$"), "?:/", "/")
end
local headers={}
headers["Accept"]="text/plain"
headers["Content-Type"]="application/x-www-form-urlencoded"
headers["Accept-Charset"]="utf-8"
local data = "message=" .. format(msg)
http.request(self.host..self.send,
function(res)
--print(res)
end,
function(res)
-- print(res)
end,
{ method="POST", headers=headers, data=data }
)
end
function Server:checkChat(interval, fn)
tween.delay(interval, function()
fn()
self:checkChat(interval, fn)
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment