Advertisement
Guest User

Untitled

a guest
Apr 1st, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.16 KB | None | 0 0
  1. ---------------------------------------------------- Библиотеки ----------------------------------------------------------------
  2.  
  3. local internet = require("internet")
  4. local json = require("json")
  5. local serialization = require("serialization")
  6. local event = require("event")
  7. local ecs = require("ECSAPI")
  8. local fs = require("filesystem")
  9. local buffer = require("doubleBuffering")
  10. local context = require("context")
  11. local image = require("image")
  12. local unicode = require("unicode")
  13. local component = require("component")
  14. local computer = require("computer")
  15.  
  16. ---------------------------------------------------- Константы ----------------------------------------------------------------
  17.  
  18. local VKAPIVersion = "5.50"
  19.  
  20. local colors = {
  21. leftBar = 0x262626,
  22. leftBarAlternative = 0x383838,
  23. leftBarText = 0xFFFFFF,
  24. leftBarSelection = 0x00A8FF,
  25. leftBarSelectionText = 0xFFFFFF,
  26.  
  27. scrollBar = 0xCCCCCC,
  28. scrollBarPipe = 0x666666,
  29.  
  30. mainZone = 0xFFFFFF,
  31. senderCloudColor = 0x3392FF,
  32. senderCloudTextColor = 0xFFFFFF,
  33. yourCloudColor = 0x55BBFF,
  34. yourCloudTextColor = 0xFFFFFF,
  35. systemMessageColor = 0x555555,
  36. dateTime = 0x777777,
  37.  
  38. loginGUIBackground = 0x002440,
  39.  
  40. topBar = 0x002440,
  41. topBarText = 0xFFFFFF,
  42.  
  43. statusBar = 0x262626,
  44. statusBarText = 0xAAAAAA,
  45.  
  46. audioPlayButton = 0x002440,
  47. audioPlayButtonText = 0xFFFFFF,
  48.  
  49. messageInputBarColor = 0xEEEEEE,
  50. messageInputBarTextBackgroundColor = 0xFFFFFF,
  51. messsageInputBarTextColor = 0x262626,
  52. }
  53.  
  54. local leftBarHeight = buffer.screen.height - 9
  55. local leftBarWidth = math.floor(buffer.screen.width * 0.17)
  56.  
  57. local topBarHeight = 3
  58.  
  59. local mainZoneWidth = buffer.screen.width - leftBarWidth
  60. local mainZoneHeight = buffer.screen.height - topBarHeight - 1
  61. local mainZoneX = leftBarWidth + 1
  62. local mainZoneY = topBarHeight + 1
  63.  
  64. local cloudWidth = math.floor(mainZoneWidth * 0.7)
  65.  
  66. -------------------------------------------------------------------------------------------------------------------------------
  67.  
  68. local VKLogoImagePath = "MineOS/Applications/VK.app/Resources/VKLogo.pic"
  69. -- local leftBarElements = {"Новости", "Друзья", "Сообщения", "Настройки", "Выход"}
  70. local leftBarElements = { "Сообщения", "Аудиозаписи", "Группы", "Выход" }
  71. local currentLeftBarElement = 1
  72. local personalInfo
  73. local access_token
  74. local whatIsOnScreen
  75.  
  76. local countOfDialogsToLoadFromServer = 10
  77. local countOfAudioToLoadFromServer = 10
  78. local countOfMessagesToLoadFromServer = 10
  79.  
  80. local dialogToShowFrom = 1
  81. local audioToShowFrom = 1
  82. local messageToShowFrom = 1
  83.  
  84. local dialogScrollSpeed = 5
  85. local audioScrollSpeed = 5
  86. local messagesScrollSpeed = 5
  87.  
  88. local currentMessagesPeerID, currentMessagesAvatarText, currentMessagesFullName
  89. local dialogPreviewTextLimit = mainZoneWidth - 15
  90.  
  91. ---------------------------------------------------- Веб-часть ----------------------------------------------------------------
  92.  
  93. --Объекты
  94. local obj = {}
  95. local function newObj(class, name, ...)
  96. obj[class] = obj[class] or {}
  97. obj[class][name] = {...}
  98. end
  99.  
  100. --Дебаг-функция на сохранение говна в файл, МАЛО ЛИ ЧО
  101. local function saveToFile(stro4ka)
  102. local file = io.open("test.lua", "w")
  103. file:write(stro4ka)
  104. file:close()
  105. end
  106.  
  107. --Модифицированная функция интернет-запросов, стандартная фу-фу-фу, ошибка на ошибке и HTTP Response Error погоняет!
  108. --Заметка: переписать на компонетное API, в рот ебал автора либы. Хм, велосипеды?
  109. local function request(url)
  110. local data = ""
  111. --Выполняем запрос на подключение
  112. local success, response = pcall(internet.request, url)
  113. --Если все ок, то делаем чтение из response, иначе выдаем ошибку, че не так с подключением
  114. --(скорее всего, ошибка будет связана с отстутствием инета или неверными URL, которые ТЫ, СУКА, лично и вбиваешь в код)
  115. if success then
  116. while true do
  117. --Делаем запрос на чтение из response
  118. local success, reason = pcall(response)
  119. --Если все ок, то идем дальше, иначе кидаем ошибку
  120. --(скорее всего, это будет серверная ошибка, неверный пасс там, 404, бла-бла)
  121. if success then
  122. --Если конец response не достигнут, то записываем в data все, что пришло с сервака, иначе по съебкам!
  123. if reason then
  124. data = data .. reason
  125. else
  126. break
  127. end
  128. else
  129. return false, reason
  130. end
  131. end
  132.  
  133. --Если все охуенно, то возвращаем true и преобразованный JSON-ответ в таблицу Lua
  134. return true, json:decode(data)
  135. else
  136. return false, response
  137. end
  138. end
  139.  
  140. --Отправляем запрос на авторизацию по логину и паролю
  141. local function getLoginDataRequest(username, password)
  142. local url = "https://oauth.vk.com/token?grant_type=password&client_id=3697615&client_secret=AlVXZFMUqyrnABp8ncuU&username=" .. username .. "&password=" .. password .. "&v=" .. VKAPIVersion
  143. return request(url)
  144. end
  145.  
  146. --Запрос к методам VK API
  147. local function VKAPIRequest(method, ... )
  148. local arguments = { ... }
  149. local stringArguments = ""
  150.  
  151. local url = "https://api.vk.com/method/" .. method .. "?" .. table.concat(arguments, "&") .. "&access_token=" .. access_token .. "&v=" .. VKAPIVersion
  152.  
  153. return request(url)
  154. end
  155.  
  156. --Запрос на получение списка диалогов
  157. local function getDialogsRequest(fromDialog, count)
  158. return VKAPIRequest("messages.getDialogs", "offset=" .. fromDialog, "count=" .. count, "preview_length=" .. dialogPreviewTextLimit)
  159. end
  160.  
  161. --Запрос на получение списка диалогов
  162. local function getMessagesRequest(peerID, fromMessage, count)
  163. return VKAPIRequest("messages.getHistory", "offset=" .. fromMessage, "count=" .. count, "peer_id=" .. peerID)
  164. end
  165.  
  166. --Запрос на получение списка музычки
  167. local function getAudioRequest(id, fromAudio, count)
  168. return VKAPIRequest("audio.get", "offset=" .. fromAudio, "count=" .. count, "owner_id=" .. id, "need_user=1")
  169. end
  170.  
  171. --Эта хуйня делает строку охуенной путем замены говна на конфетку
  172. local function optimizeStringForURLSending(code)
  173. if code then
  174. code = string.gsub(code, "([^%w ])", function (c)
  175. return string.format("%%%02X", string.byte(c))
  176. end)
  177. code = string.gsub(code, " ", "+")
  178. end
  179. return code
  180. end
  181.  
  182. local function optimizeStringForWrongSymbols(s)
  183. --Удаляем некорректные символы
  184. s = string.gsub(s, " ", " ")
  185. s = string.gsub(s, "\r\n", "\n")
  186. s = string.gsub(s, "\n", "")
  187. --Заменяем "широкие" двухпиксельные символы на знак вопроса
  188. local massiv = {}
  189. for i = 1, unicode.len(s) do
  190. massiv[i] = unicode.sub(s, i, i)
  191. if unicode.isWide(massiv[i]) then massiv[i] = "?" end
  192. end
  193. --Возвращаем оптимизрованную строку
  194. return table.concat(massiv)
  195. end
  196.  
  197. local function convertIDtoPeerID(whatIsThisID, ID)
  198. if whatIsThisID == "user" then
  199. return ID
  200. elseif whatIsThisID == "chat" then
  201. return (2000000000 + ID)
  202. elseif whatIsThisID == "group" then
  203. return -ID
  204. end
  205. end
  206.  
  207. local function getPeerIDFromMessageArray(messageArray)
  208. local peerID
  209. --Если это чат
  210. if messageArray.users_count then
  211. peerID = convertIDtoPeerID("chat", messageArray.chat_id)
  212. --Или если это диалог с группой какой-то
  213. elseif messageArray.user_id < 0 then
  214. peerID = convertIDtoPeerID("group", messageArray.user_id)
  215. --Или если просто какой-то сталкер-одиночка
  216. else
  217. peerID = convertIDtoPeerID("user", messageArray.user_id)
  218. end
  219.  
  220. return peerID
  221. end
  222.  
  223. --Запрос на отправку сообщения указанному пидору
  224. local function sendMessageRequest(peerID, message)
  225. --Делаем строчку не пидорской
  226. message = optimizeStringForURLSending(message)
  227. return VKAPIRequest("messages.send", "peer_id=" .. peerID, "message=" .. message)
  228. end
  229.  
  230. local function usersInformationRequest(...)
  231. return VKAPIRequest("users.get", "user_ids=" .. table.concat({...}, ","), "fields=city,bdate,online,status,last_seen,followers_count")
  232. end
  233.  
  234. ---------------------------------------------------- GUI-часть ----------------------------------------------------------------
  235.  
  236. local function createAvatarHashColor(hash)
  237. return math.abs(hash % 0xFFFFFF)
  238. end
  239.  
  240. local function drawAvatar(x, y, user_id, text)
  241. local avatarColor = createAvatarHashColor(user_id)
  242. local textColor = avatarColor > 8388607 and 0x000000 or 0xFFFFFF
  243.  
  244. buffer.square(x, y, 6, 3, avatarColor, textColor, " ")
  245. buffer.text(x + 2, y + 1, textColor, unicode.upper(text))
  246. end
  247.  
  248. --Проверка клика в определенную область по "объекту". Кому на хуй вссалось ООП?
  249. local function clickedAtZone(x, y, zone)
  250. if x >= zone[1] and y >= zone[2] and x <= zone[3] and y <= zone[4] then
  251. return true
  252. end
  253. return false
  254. end
  255.  
  256. --Интерфейс логина в аккаунт ВК, постараюсь сделать пографонистей
  257. --Хотя хах! Кого я обманываю, ага
  258. local function loginGUI(startUsername, startPassword)
  259. local background = 0x002440
  260. local buttonColor = 0x666DFF
  261. local textColor = 0x262626
  262. local username, password = startUsername or "E-Mail или номер телефона", startPassword or "Пароль"
  263.  
  264. local textFieldWidth = 50
  265. local textFieldHeight = 3
  266. local x, y = math.floor(buffer.screen.width / 2 - textFieldWidth / 2), math.floor(buffer.screen.height / 2 - 3)
  267.  
  268. local obj = {}
  269. obj.username = {x, y, x + textFieldWidth - 1, y + 2}; y = y + textFieldHeight + 1
  270. obj.password = {x, y, x + textFieldWidth - 1, y + 2}; y = y + textFieldHeight + 1
  271. obj.button = {x, y, x + textFieldWidth - 1, y + 2}
  272.  
  273. local VKLogoImage = image.load(VKLogoImagePath)
  274.  
  275. local function draw()
  276. buffer.clear(colors.loginGUIBackground)
  277.  
  278. buffer.image(x + 5, obj.username[2] - 15, VKLogoImage)
  279.  
  280. buffer.square(x, obj.username[2], textFieldWidth, 3, 0xFFFFFF, 0x000000, " ")
  281. buffer.square(x, obj.password[2], textFieldWidth, 3, 0xFFFFFF, 0x000000, " ")
  282. buffer.text(x + 1, obj.username[2] + 1, textColor, ecs.stringLimit("end", username, textFieldWidth - 2))
  283. buffer.text(x + 1, obj.password[2] + 1, textColor, ecs.stringLimit("end", string.rep("●", unicode.len(password)), textFieldWidth - 2))
  284.  
  285. buffer.button(x, obj.button[2], textFieldWidth, textFieldHeight, buttonColor, 0xFFFFFF, "Войти")
  286.  
  287. buffer.draw()
  288. end
  289.  
  290. while true do
  291. draw()
  292. local e = {event.pull()}
  293. if e[1] == "touch" then
  294. if clickedAtZone(e[3], e[4], obj.username) then
  295. username = ""
  296. username = ecs.inputText(x + 1, obj.username[2] + 1, textFieldWidth - 2, username, 0xFFFFFF, 0x262626) or ""
  297.  
  298. elseif clickedAtZone(e[3], e[4], obj.password) then
  299. password = ""
  300. password = ecs.inputText(x + 1, obj.password[2] + 1, textFieldWidth - 2, password, 0xFFFFFF, 0x262626, false, "*") or ""
  301.  
  302. elseif clickedAtZone(e[3], e[4], obj.button) then
  303. buffer.button(x, obj.button[2], textFieldWidth, textFieldHeight, 0xFFFFFF, buttonColor, "Войти")
  304. buffer.draw()
  305. os.sleep(0.2)
  306. draw()
  307. local success, loginData = getLoginDataRequest(username, password)
  308. if success then
  309. return loginData
  310. else
  311. ecs.error("Неверный пароль!" .. tostring(loginData))
  312. end
  313. end
  314. end
  315. end
  316. end
  317.  
  318. ---------------------------------------------------- GUI для взаимодействия с VK API ----------------------------------------------
  319.  
  320. local function drawPersonalAvatar(x, y)
  321. drawAvatar(x, y, personalInfo.id, unicode.sub(personalInfo.first_name, 1, 1) .. unicode.sub(personalInfo.last_name, 1, 1))
  322. end
  323.  
  324. local function status(text)
  325. buffer.square(mainZoneX, buffer.screen.height, mainZoneWidth, 1, colors.statusBar)
  326. buffer.text(mainZoneX + 1, buffer.screen.height, colors.statusBarText, text)
  327. buffer.draw()
  328. end
  329.  
  330. local function drawTopBar(text)
  331. buffer.square(mainZoneX, 1, mainZoneWidth, 3, colors.topBar)
  332. local x = math.floor(mainZoneX + mainZoneWidth / 2 - unicode.len(text) / 2 - 1)
  333. buffer.text(x, 2, colors.topBarText, text)
  334. end
  335.  
  336. --Рисуем главную зону
  337. local function clearGUIZone()
  338. buffer.square(mainZoneX, mainZoneY, mainZoneWidth, mainZoneHeight, colors.mainZone)
  339. end
  340.  
  341.  
  342.  
  343.  
  344.  
  345.  
  346.  
  347. local function drawEmptyCloud(x, y, cloudWidth, cloudHeight, cloudColor, fromYou)
  348. local upperPixel = "▀"
  349. local lowerPixel = "▄"
  350.  
  351. --Рисуем финтифлюшечки
  352. if not fromYou then
  353. buffer.set(x, y - cloudHeight + 2, colors.mainZone, cloudColor, upperPixel)
  354. buffer.set(x + 1, y - cloudHeight + 2, cloudColor, 0xFFFFFF, " ")
  355. x = x + 2
  356. else
  357. buffer.set(x + cloudWidth + 3, y - cloudHeight + 2, colors.mainZone, cloudColor, upperPixel)
  358. buffer.set(x + cloudWidth + 2, y - cloudHeight + 2, cloudColor, 0xFFFFFF, " ")
  359. end
  360.  
  361. --Заполняшечки
  362. buffer.square(x + 1, y - cloudHeight + 1, cloudWidth, cloudHeight, cloudColor, 0xFFFFFF, " ")
  363. buffer.square(x, y - cloudHeight + 2, cloudWidth + 2, cloudHeight - 2, cloudColor, 0xFFFFFF, " ")
  364.  
  365. --Сгругленные краешки
  366. buffer.set(x, y - cloudHeight + 1, colors.mainZone, cloudColor, lowerPixel)
  367. buffer.set(x + cloudWidth + 1, y - cloudHeight + 1, colors.mainZone, cloudColor, lowerPixel)
  368. buffer.set(x, y, colors.mainZone, cloudColor, upperPixel)
  369. buffer.set(x + cloudWidth + 1, y, colors.mainZone, cloudColor, upperPixel)
  370.  
  371. return y - cloudHeight + 1
  372. end
  373.  
  374. local function stringWrap(text, limit)
  375. local strings = {}
  376. local textLength = unicode.len(text)
  377. local subFrom = 1
  378. while subFrom <= textLength do
  379. table.insert(strings, unicode.sub(text, subFrom, subFrom + limit - 1))
  380. subFrom = subFrom + limit
  381. end
  382. return strings
  383. end
  384.  
  385. local function drawTextCloud(x, y, cloudColor, textColor, fromYou, text)
  386. local y = drawEmptyCloud(x, y, cloudWidth, #text + 2, cloudColor, fromYou)
  387. x = fromYou and x + 2 or x + 4
  388.  
  389. for i = 1, #text do
  390. buffer.text(x, y + i, textColor, text[i])
  391. end
  392.  
  393. return y
  394. end
  395.  
  396. local function getAttachments(messageArray)
  397. local text = "Вложения: "
  398. for j = 1, #messageArray.attachments do
  399. if messageArray.attachments[j].type == "sticker" then
  400. text = text .. "стикер, "
  401. elseif messageArray.attachments[j].type == "photo" then
  402. text = text .. "фото, "
  403. elseif messageArray.attachments[j].type == "video" then
  404. text = text .. "видео, "
  405. elseif messageArray.attachments[j].type == "audio" then
  406. text = text .. "аудио, "
  407. elseif messageArray.attachments[j].type == "wall" then
  408. text = text .. "запись на стене, "
  409. end
  410. end
  411. text = unicode.sub(text, 1, -3)
  412.  
  413. return text
  414. end
  415.  
  416. local function drawMessageInputBar(currentText)
  417. local x, y = mainZoneX, buffer.screen.height - 5
  418. obj.messageInputBar = { x, y, x + mainZoneWidth - 7, y + 2}
  419. buffer.square(x, y, mainZoneWidth, 5, colors.messageInputBarColor)
  420. buffer.square(x + 2, y + 1, mainZoneWidth - 4, 3, colors.messageInputBarTextBackgroundColor)
  421. buffer.text(x + 4, y + 2, colors.messsageInputBarTextColor, ecs.stringLimit("start", currentText or "Введите сообщение", mainZoneWidth - 8))
  422. end
  423.  
  424. local function getUserNamesFromMessagesArray(messagesArray)
  425. local usersToGetNames = {}
  426. for i = 1, #messagesArray do
  427. if messagesArray[i].user_id and messagesArray[i].user_id > 0 then
  428. table.insert(usersToGetNames, messagesArray[i].user_id)
  429. end
  430. end
  431.  
  432. local success, usersData = usersInformationRequest(table.unpack(usersToGetNames))
  433. if success and usersData.response then
  434. for i = 1, #messagesArray do
  435. if messagesArray[i].user_id and messagesArray[i].user_id > 0 then
  436. for j = 1, #usersData.response do
  437. if usersData.response[j].id == messagesArray[i].user_id then
  438. messagesArray[i].first_name = usersData.response[j].first_name
  439. messagesArray[i].last_name = usersData.response[j].last_name
  440. end
  441. end
  442. end
  443. end
  444. end
  445.  
  446. return messagesArray
  447. end
  448.  
  449. local function messagesGUI()
  450.  
  451. local success, messages = getMessagesRequest(currentMessagesPeerID, messageToShowFrom - 1, countOfMessagesToLoadFromServer)
  452. if success and messages.response then
  453.  
  454. whatIsOnScreen = "messages"
  455.  
  456. if currentMessagesPeerID > 2000000000 then
  457. status("Загружаю имена пользователей из переписки (актуально для конференций)")
  458. messages.response.items = getUserNamesFromMessagesArray(messages.response.items)
  459. end
  460.  
  461. clearGUIZone()
  462. drawTopBar("Диалог с \"" .. currentMessagesFullName .. "\"")
  463.  
  464. saveToFile(serialization.serialize(messages))
  465.  
  466. buffer.setDrawLimit(mainZoneX, mainZoneY, mainZoneWidth, mainZoneHeight)
  467.  
  468. local y = buffer.screen.height - 7
  469. local xSender = mainZoneX + 2
  470. local xYou = buffer.screen.width - 7
  471.  
  472. for i = 1, #messages.response.items do
  473.  
  474. local messageTextArray = {}
  475.  
  476. if messages.response.items[i].body ~= "" then table.insert(messageTextArray, optimizeStringForWrongSymbols(messages.response.items[i].body)) end
  477. if messages.response.items[i].fwd_messages then table.insert(messageTextArray, "Пересланные сообщения") end
  478. if messages.response.items[i].attachments then table.insert(messageTextArray, getAttachments(messages.response.items[i])) end
  479.  
  480. messageTextArray = ecs.stringWrap(messageTextArray, cloudWidth - 4)
  481. local peerID = getPeerIDFromMessageArray(messages.response.items[i])
  482.  
  483. --Делаем дату пиздатой
  484. -- messages.response.items[i].date = os.date("%d.%m.%y в %X", messages.response.items[i].date)
  485. messages.response.items[i].date = os.date("%H:%M", messages.response.items[i].date)
  486.  
  487. if messages.response.items[i].out == 1 then
  488. y = drawTextCloud(xYou - cloudWidth - 6, y, colors.yourCloudColor, colors.yourCloudTextColor, true, messageTextArray)
  489. drawPersonalAvatar(xYou, y)
  490. buffer.text(xYou - cloudWidth - unicode.len(messages.response.items[i].date) - 8, y + 1, colors.dateTime, messages.response.items[i].date)
  491. else
  492. y = drawTextCloud(xSender + 8, y, colors.senderCloudColor, colors.senderCloudTextColor, false, messageTextArray)
  493. drawAvatar(xSender, y, peerID, messages.response.items[i].first_name and (unicode.sub(messages.response.items[i].first_name, 1, 1) .. unicode.sub(messages.response.items[i].last_name, 1, 1)) or currentMessagesAvatarText)
  494. buffer.text(xSender + cloudWidth + 14, y + 1, colors.dateTime, messages.response.items[i].date)
  495. end
  496.  
  497. y = y - 2
  498. end
  499.  
  500. local currentText
  501.  
  502. drawMessageInputBar(currentText)
  503.  
  504. status("История переписки загружена, ожидаю ввода сообщения")
  505.  
  506. buffer.resetDrawLimit()
  507. -- buffer.draw()
  508. end
  509. end
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516. --У-у-у, господи, какие же уроды! Вроде такое охуенное вк апи, а пиздец!
  517. --Крч, эта функция получает имена юзеров по их айдишникам и загоняет их
  518. --в массив вместо title.
  519. --Собсна, нахуя? ДА ПОТОМУ ЧТО dialogs возвращают только ID юзеров с историей
  520. --сообщений, а не их имя. Ну, а имена КОНФ нормас пишутся. Что за бред?
  521. --Идите на хуйЙ!!!!!! КОСТЫЛЕЕБСТВО
  522. local function getUserNamesFromDialogArray(dialogs)
  523. local usersToGetNames = {}
  524.  
  525. for i = 1, #dialogs.response.items do
  526. if dialogs.response.items[i].message.user_id and dialogs.response.items[i].message.user_id > 0 then
  527. table.insert(usersToGetNames, dialogs.response.items[i].message.user_id)
  528. end
  529. end
  530.  
  531. local success, usersData = usersInformationRequest(table.unpack(usersToGetNames))
  532. if success and usersData.response then
  533. for i = 1, #dialogs.response.items do
  534. if not dialogs.response.items[i].message.chat_id then
  535. for j = 1, #usersData.response do
  536. if usersData.response[j].id == dialogs.response.items[i].message.user_id then
  537. dialogs.response.items[i].message.title = usersData.response[j].first_name .. " " .. usersData.response[j].last_name
  538. end
  539. end
  540. end
  541. end
  542. end
  543.  
  544. return dialogs
  545. end
  546.  
  547. local function drawDialog(y, dialogBackground, avatarID, avatarText, text1, text2, text3)
  548. --Рисуем подложку под диалог нужного цвета
  549. buffer.square(mainZoneX, y, mainZoneWidth, 5, dialogBackground)
  550. --Рисуем аватарку, чо уж
  551. drawAvatar(mainZoneX + 2, y + 1, avatarID, avatarText)
  552. --Пишем все, что нужно
  553. y = y + 1
  554. if text1 then buffer.text(mainZoneX + 10, y, 0x000000, text1); y = y + 1 end
  555. if text2 then buffer.text(mainZoneX + 10, y, 0x555555, text2); y = y + 1 end
  556. if text3 then buffer.text(mainZoneX + 10, y, 0x666666, text3); y = y + 1 end
  557. end
  558.  
  559. local function dialogsGUI()
  560.  
  561. local success, dialogs = getDialogsRequest(dialogToShowFrom - 1, countOfDialogsToLoadFromServer)
  562. if success and dialogs.response then
  563.  
  564. -- saveToFile(serialization.serialize(dialogs))
  565.  
  566. whatIsOnScreen = "dialogs"
  567.  
  568. obj.dialogList = {}
  569.  
  570. clearGUIZone()
  571. drawTopBar("Сообщения")
  572. buffer.draw()
  573.  
  574. --НУ ТЫ ПОНЯЛ, АГА
  575. status("Получаю имена пользователей по ID")
  576. dialogs = getUserNamesFromDialogArray(dialogs)
  577.  
  578. local y = mainZoneY
  579. local avatarText = ""
  580. local peerID
  581. local color
  582.  
  583. for i = 1, #dialogs.response.items do
  584. --Ебемся с цветами
  585. if dialogs.response.items[i].unread then
  586. if i % 2 == 0 then
  587. color = 0xCCDBFF
  588. else
  589. color = 0xCCDBFF
  590. end
  591. else
  592. if i % 2 == 0 then
  593. color = 0xEEEEEE
  594. else
  595. color = 0xFFFFFF
  596. end
  597. end
  598.  
  599. --Рисуем пиздюлинку, показывающую кол-во непрочитанных сообщений
  600. if dialogs.response.items[i].unread and dialogs.response.items[i].unread ~= 0 then
  601. local cyka = tostring(dialogs.response.items[i].unread)
  602. local cykaWidth = unicode.len(cyka) + 2
  603. local cykaX = buffer.screen.width - cykaWidth - 4
  604. buffer.square(cykaX, y + 2, cykaWidth, 1, ecs.colors.blue)
  605. buffer.text(cykaX + 1, y + 2, 0xFFFFFF, cyka)
  606. end
  607.  
  608.  
  609. avatarText = unicode.sub(dialogs.response.items[i].message.title, 1, 2)
  610. peerID = getPeerIDFromMessageArray(dialogs.response.items[i].message)
  611.  
  612. --Ебля с текстом диалога
  613. local text1 = dialogs.response.items[i].message.title
  614. local text2
  615. local text3
  616.  
  617. --Если это банальное сообщение
  618. if dialogs.response.items[i].message.body and dialogs.response.items[i].message.body ~= "" then
  619. text2 = optimizeStringForWrongSymbols(dialogs.response.items[i].message.body)
  620. end
  621.  
  622. --Если есть какие-либо пересланные сообщения, то
  623. if dialogs.response.items[i].message.fwd_messages then
  624. text3 = "Пересланные сообщения"
  625. --Если есть какие-либо вложения, то
  626. elseif dialogs.response.items[i].message.attachments then
  627. text3 = getAttachments(dialogs.response.items[i].message)
  628. end
  629.  
  630. --Рисуем диалог
  631. drawDialog(y, color, peerID, avatarText, text1, text2, text3)
  632.  
  633. newObj("dialogList", i, mainZoneX, y, mainZoneX + mainZoneWidth - 1, y + 4, peerID, avatarText, text1, text2, text3)
  634.  
  635. y = y + 5
  636. end
  637. end
  638.  
  639. status("Список диалогов получен")
  640. end
  641.  
  642. local function audioGUI(ID)
  643. local success, audios = getAudioRequest(ID, audioToShowFrom - 1, countOfAudioToLoadFromServer)
  644. if success and audios.response then
  645. whatIsOnScreen = "audio"
  646.  
  647. obj.audio = {}
  648.  
  649. clearGUIZone()
  650. drawTopBar("Аудиозаписи " .. audios.response.items[1].name_gen)
  651.  
  652. local y = mainZoneY
  653. local color
  654. for i = 2, #audios.response.items do
  655. color = 0xFFFFFF
  656. if i % 2 == 0 then color = 0xEEEEEE end
  657.  
  658. buffer.square(mainZoneX, y, mainZoneWidth, 5, color)
  659.  
  660. buffer.button(mainZoneX + 2, y + 1, 5, 3, colors.audioPlayButton, colors.audioPlayButtonText, "ᐅ")
  661.  
  662. newObj("audio", i, mainZoneX + 2, y + 1, mainZoneX + 7, y + 3, audios.response.items[i].url)
  663.  
  664. local x = mainZoneX + 9
  665. buffer.text(x, y + 1, colors.audioPlayButton, audios.response.items[i].artist)
  666. x = x + unicode.len(audios.response.items[i].artist)
  667. buffer.text(x, y + 1, 0x000000, " - " .. audios.response.items[i].title)
  668.  
  669. x = mainZoneX + 9
  670. local hours = string.format("%02.f", math.floor(audios.response.items[i].duration / 3600))
  671. local minutes = string.format("%02.f", math.floor(audios.response.items[i].duration / 60 - (hours * 60)))
  672. local seconds = string.format("%02.f", math.floor(audios.response.items[i].duration - hours * 3600 - minutes * 60))
  673. buffer.text(x, y + 2, 0x555555, "Длительность: " .. hours .. ":" .. minutes .. ":" .. seconds)
  674.  
  675. y = y + 5
  676. end
  677. end
  678. end
  679.  
  680. --Главное ГУИ с левтбаром и прочим
  681. local function mainGUI()
  682. --Подложка под элементы
  683. buffer.square(1, 1, leftBarWidth, buffer.screen.height, colors.leftBar, 0xFFFFFF, " ")
  684.  
  685. if personalInfo then
  686. drawPersonalAvatar(3, 2)
  687. buffer.text(11, 3, 0xFFFFFF, ecs.stringLimit("end", personalInfo.first_name .. " " .. personalInfo.last_name, leftBarWidth - 11))
  688. end
  689.  
  690. --Элементы
  691. obj.leftBar = {}
  692. local y, color = 6
  693. for i = 1, #leftBarElements do
  694. color = colors.leftBarAlternative
  695. if i % 2 == 0 then color = colors.leftBar end
  696. if i == currentLeftBarElement then color = colors.leftBarSelection end
  697.  
  698. newObj("leftBar", i, 1, y, leftBarWidth, y + 2)
  699.  
  700. buffer.square(1, y, leftBarWidth, 3, color, 0xFFFFFF, " ")
  701. y = y + 1
  702. buffer.text(3, y, colors.leftBarText, ecs.stringLimit("end", leftBarElements[i], leftBarWidth - 4))
  703. y = y + 2
  704. end
  705.  
  706. if leftBarElements[currentLeftBarElement] == "Сообщения" then
  707. status("Получаю список диалогов")
  708. messageToShowFrom = 1
  709. dialogToShowFrom = 1
  710. dialogsGUI()
  711. elseif leftBarElements[currentLeftBarElement] == "Аудиозаписи" then
  712. status("Получаю список аудозаписей")
  713. audioToShowFrom = 1
  714. audioGUI(personalInfo.id)
  715. end
  716.  
  717. buffer.draw()
  718. end
  719.  
  720. ---------------------------------------------------- Старт скрипта ----------------------------------------------------------------
  721.  
  722. --Инициализируем библиотеку двойного буффера
  723. --Эх, что бы я делал, если б не накодил ее? 0.2 фпс на GPU мертвеца!
  724. buffer.start()
  725. --Активируем форму логина
  726. local loginData = loginGUI("igor_timofeev@me.com", "13131313")
  727. access_token = loginData.access_token
  728. --Получаем персональные данные
  729. _, personalInfo = usersInformationRequest(loginData.user_id)
  730. personalInfo = personalInfo.response[1]
  731.  
  732. --Активируем главное GUI
  733. clearGUIZone()
  734. mainGUI()
  735.  
  736. while true do
  737. local e = {event.pull()}
  738. if e[1] == "touch" then
  739.  
  740. if whatIsOnScreen == "audio" then
  741. for key in pairs(obj.audio) do
  742. if clickedAtZone(e[3], e[4], obj.audio[key]) then
  743. buffer.button(obj.audio[key][1], obj.audio[key][2], 5, 3, 0x66FF80, colors.audioPlayButton, "ᐅ")
  744. buffer.draw()
  745. os.sleep(0.2)
  746. buffer.button(obj.audio[key][1], obj.audio[key][2], 5, 3, colors.audioPlayButton, colors.audioPlayButtonText, "ᐅ")
  747. buffer.draw()
  748.  
  749. if component.isAvailable("openfm_radio") then
  750. component.openfm_radio.stop()
  751. component.openfm_radio.setURL(obj.audio[key][5])
  752. component.openfm_radio.start()
  753. else
  754. ecs.error("Эта функция доступна только при наличии установленного мода OpenFM, добавляющего полноценное интернет-радио")
  755. end
  756.  
  757. break
  758. end
  759. end
  760. end
  761.  
  762. if whatIsOnScreen == "dialogs" then
  763. for key in pairs(obj.dialogList) do
  764. if clickedAtZone(e[3], e[4], obj.dialogList[key]) then
  765. drawDialog(obj.dialogList[key][2], 0xFF8888, obj.dialogList[key][5], obj.dialogList[key][6], obj.dialogList[key][7], obj.dialogList[key][8], obj.dialogList[key][9])
  766. buffer.draw()
  767. os.sleep(0.2)
  768. status("Загружаю переписку с пользователем " .. obj.dialogList[key][7])
  769. currentMessagesPeerID = obj.dialogList[key][5]
  770. currentMessagesAvatarText = obj.dialogList[key][6]
  771. currentMessagesFullName = obj.dialogList[key][7]
  772. messagesGUI()
  773. break
  774. end
  775. end
  776. end
  777.  
  778. if whatIsOnScreen == "messages" then
  779. if clickedAtZone(e[3], e[4], obj.messageInputBar) then
  780. drawMessageInputBar(" ")
  781. buffer.draw()
  782. local newText = ecs.inputText(obj.messageInputBar[1] + 4, obj.messageInputBar[2] + 2, obj.messageInputBar[3] - obj.messageInputBar[1], "", colors.messageInputBarTextBackgroundColor, colors.messsageInputBarTextColor)
  783. if newText and newText ~= " " then
  784. computer.beep(1700)
  785. status("Отправляю сообщение пользователю")
  786. sendMessageRequest(currentMessagesPeerID, newText .. " (отправлено с OpenComputers)")
  787. status("Обновляю историю переписки")
  788. messageToShowFrom = 1
  789. messagesGUI()
  790. end
  791. drawMessageInputBar(" ")
  792. end
  793. end
  794.  
  795. for key in pairs(obj.leftBar) do
  796. if clickedAtZone(e[3], e[4], obj.leftBar[key]) then
  797. -- ecs.error("Кликнули на лефт бар ээлемент")
  798. currentLeftBarElement = key
  799. mainGUI()
  800.  
  801. if leftBarElements[currentLeftBarElement] == "Выход" then
  802. os.sleep(0.3)
  803. buffer.clear(0x262626)
  804. ecs.prepareToExit()
  805. return
  806. end
  807.  
  808. break
  809. end
  810. end
  811. elseif e[1] == "scroll" then
  812. if e[5] == 1 then
  813. if whatIsOnScreen == "dialogs" then
  814. dialogToShowFrom = dialogToShowFrom - dialogScrollSpeed
  815. if dialogToShowFrom < 1 then dialogToShowFrom = 1 end
  816. status("Прокручиваю диалоги, отправляю запрос на сервер")
  817. dialogsGUI()
  818. buffer.draw()
  819. elseif whatIsOnScreen == "messages" then
  820. messageToShowFrom = messageToShowFrom + messagesScrollSpeed
  821. status("Прокручиваю сообщения, отправляю запрос на сервер")
  822. messagesGUI()
  823. buffer.draw()
  824. elseif whatIsOnScreen == "audio" then
  825. audioToShowFrom = audioToShowFrom - audioScrollSpeed
  826. if audioToShowFrom < 1 then audioToShowFrom = 1 end
  827. status("Прокручиваю аудозаписи, отправляю запрос на сервер")
  828. audioGUI(personalInfo.id)
  829. buffer.draw()
  830. end
  831. else
  832. if whatIsOnScreen == "dialogs" then
  833. dialogToShowFrom = dialogToShowFrom + dialogScrollSpeed
  834. status("Прокручиваю диалоги, отправляю запрос на сервер")
  835. dialogsGUI()
  836. buffer.draw()
  837. elseif whatIsOnScreen == "messages" then
  838. messageToShowFrom = messageToShowFrom - messagesScrollSpeed
  839. if messageToShowFrom < 1 then messageToShowFrom = 1 end
  840. status("Прокручиваю сообщения, отправляю запрос на сервер")
  841. messagesGUI()
  842. buffer.draw()
  843. elseif whatIsOnScreen == "audio" then
  844. audioToShowFrom = audioToShowFrom + audioScrollSpeed
  845. status("Прокручиваю аудозаписи, отправляю запрос на сервер")
  846. audioGUI(personalInfo.id)
  847. buffer.draw()
  848. end
  849. end
  850. end
  851. end
  852.  
  853. -- local success, dialogs = getDialogsRequest(0, 5)
  854. -- saveToFile(serialization.serialize(dialogs))
  855.  
  856.  
  857. -- sendMessageRequest(dialogs.response.items[2], "тестовое сообщение, отправлено через OpenComputers VK Client by Игорь, епта")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement