16 skills found
bilalsammour / DobListDobLis is an Open Source Android library that provides to ListView adding ProgressBar (or any view) to the footer of ListView to be shown in loading more, and callback that is called when reaching last item in ListView.
arashstar1 / Bot LuaCode Issues 0 Pull requests 0 Pulse MaTaDoR/ 3233fdf V 5.7 MaTaDoR @MaTaDoRTeaMMaTaDoRTeaM committed on GitHub about 1 month ago 2 changed files 2,704 additions and 0 deletions cli/tg/tdcli.lua @@ -0,0 +1,2704 @@ +--[[ + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. + +]]-- + +-- Vector example form is like this: {[0] = v} or {v1, v2, v3, [0] = v} +-- If false or true crashed your telegram-cli, try to change true to 1 and false to 0 + +-- Main Bot Framework +local M = {} + +-- @chat_id = user, group, channel, and broadcast +-- @group_id = normal group +-- @channel_id = channel and broadcast +local function getChatId(chat_id) + local chat = {} + local chat_id = tostring(chat_id) + + if chat_id:match('^-100') then + local channel_id = chat_id:gsub('-100', '') + chat = {ID = channel_id, type = 'channel'} + else + local group_id = chat_id:gsub('-', '') + chat = {ID = group_id, type = 'group'} + end + + return chat +end + +local function getInputFile(file) + if file:match('/') then + infile = {ID = "InputFileLocal", path_ = file} + elseif file:match('^%d+$') then + infile = {ID = "InputFileId", id_ = file} + else + infile = {ID = "InputFilePersistentId", persistent_id_ = file} + end + + return infile +end + +-- User can send bold, italic, and monospace text uses HTML or Markdown format. +local function getParseMode(parse_mode) + if parse_mode then + local mode = parse_mode:lower() + + if mode == 'markdown' or mode == 'md' then + P = {ID = "TextParseModeMarkdown"} + elseif mode == 'html' then + P = {ID = "TextParseModeHTML"} + end + end + + return P +end + +-- Returns current authorization state, offline request +local function getAuthState(dl_cb, cmd) + tdcli_function ({ + ID = "GetAuthState", + }, dl_cb, cmd) +end + +M.getAuthState = getAuthState + +-- Sets user's phone number and sends authentication code to the user. +-- Works only when authGetState returns authStateWaitPhoneNumber. +-- If phone number is not recognized or another error has happened, returns an error. Otherwise returns authStateWaitCode +-- @phone_number User's phone number in any reasonable format +-- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number +-- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False +local function setAuthPhoneNumber(phone_number, allow_flash_call, is_current_phone_number, dl_cb, cmd) + tdcli_function ({ + ID = "SetAuthPhoneNumber", + phone_number_ = phone_number, + allow_flash_call_ = allow_flash_call, + is_current_phone_number_ = is_current_phone_number + }, dl_cb, cmd) +end + +M.setAuthPhoneNumber = setAuthPhoneNumber + +-- Resends authentication code to the user. +-- Works only when authGetState returns authStateWaitCode and next_code_type of result is not null. +-- Returns authStateWaitCode on success +local function resendAuthCode(dl_cb, cmd) + tdcli_function ({ + ID = "ResendAuthCode", + }, dl_cb, cmd) +end + +M.resendAuthCode = resendAuthCode + +-- Checks authentication code. +-- Works only when authGetState returns authStateWaitCode. +-- Returns authStateWaitPassword or authStateOk on success +-- @code Verification code from SMS, Telegram message, voice call or flash call +-- @first_name User first name, if user is yet not registered, 1-255 characters +-- @last_name Optional user last name, if user is yet not registered, 0-255 characters +local function checkAuthCode(code, first_name, last_name, dl_cb, cmd) + tdcli_function ({ + ID = "CheckAuthCode", + code_ = code, + first_name_ = first_name, + last_name_ = last_name + }, dl_cb, cmd) +end + +M.checkAuthCode = checkAuthCode + +-- Checks password for correctness. +-- Works only when authGetState returns authStateWaitPassword. +-- Returns authStateOk on success +-- @password Password to check +local function checkAuthPassword(password, dl_cb, cmd) + tdcli_function ({ + ID = "CheckAuthPassword", + password_ = password + }, dl_cb, cmd) +end + +M.checkAuthPassword = checkAuthPassword + +-- Requests to send password recovery code to email. +-- Works only when authGetState returns authStateWaitPassword. +-- Returns authStateWaitPassword on success +local function requestAuthPasswordRecovery(dl_cb, cmd) + tdcli_function ({ + ID = "RequestAuthPasswordRecovery", + }, dl_cb, cmd) +end + +M.requestAuthPasswordRecovery = requestAuthPasswordRecovery + +-- Recovers password with recovery code sent to email. +-- Works only when authGetState returns authStateWaitPassword. +-- Returns authStateOk on success +-- @recovery_code Recovery code to check +local function recoverAuthPassword(recovery_code, dl_cb, cmd) + tdcli_function ({ + ID = "RecoverAuthPassword", + recovery_code_ = recovery_code + }, dl_cb, cmd) +end + +M.recoverAuthPassword = recoverAuthPassword + +-- Logs out user. +-- If force == false, begins to perform soft log out, returns authStateLoggingOut after completion. +-- If force == true then succeeds almost immediately without cleaning anything at the server, but returns error with code 401 and description "Unauthorized" +-- @force If true, just delete all local data. Session will remain in list of active sessions +local function resetAuth(force, dl_cb, cmd) + tdcli_function ({ + ID = "ResetAuth", + force_ = force or nil + }, dl_cb, cmd) +end + +M.resetAuth = resetAuth + +-- Check bot's authentication token to log in as a bot. +-- Works only when authGetState returns authStateWaitPhoneNumber. +-- Can be used instead of setAuthPhoneNumber and checkAuthCode to log in. +-- Returns authStateOk on success +-- @token Bot token +local function checkAuthBotToken(token, dl_cb, cmd) + tdcli_function ({ + ID = "CheckAuthBotToken", + token_ = token + }, dl_cb, cmd) +end + +M.checkAuthBotToken = checkAuthBotToken + +-- Returns current state of two-step verification +local function getPasswordState(dl_cb, cmd) + tdcli_function ({ + ID = "GetPasswordState", + }, dl_cb, cmd) +end + +M.getPasswordState = getPasswordState + +-- Changes user password. +-- If new recovery email is specified, then error EMAIL_UNCONFIRMED is returned and password change will not be applied until email confirmation. +-- Application should call getPasswordState from time to time to check if email is already confirmed +-- @old_password Old user password +-- @new_password New user password, may be empty to remove the password +-- @new_hint New password hint, can be empty +-- @set_recovery_email Pass True, if recovery email should be changed +-- @new_recovery_email New recovery email, may be empty +local function setPassword(old_password, new_password, new_hint, set_recovery_email, new_recovery_email, dl_cb, cmd) + tdcli_function ({ + ID = "SetPassword", + old_password_ = old_password, + new_password_ = new_password, + new_hint_ = new_hint, + set_recovery_email_ = set_recovery_email, + new_recovery_email_ = new_recovery_email + }, dl_cb, cmd) +end + +M.setPassword = setPassword + +-- Returns set up recovery email. +-- This method can be used to verify a password provided by the user +-- @password Current user password +local function getRecoveryEmail(password, dl_cb, cmd) + tdcli_function ({ + ID = "GetRecoveryEmail", + password_ = password + }, dl_cb, cmd) +end + +M.getRecoveryEmail = getRecoveryEmail + +-- Changes user recovery email. +-- If new recovery email is specified, then error EMAIL_UNCONFIRMED is returned and email will not be changed until email confirmation. +-- Application should call getPasswordState from time to time to check if email is already confirmed. +-- If new_recovery_email coincides with the current set up email succeeds immediately and aborts all other requests waiting for email confirmation +-- @password Current user password +-- @new_recovery_email New recovery email +local function setRecoveryEmail(password, new_recovery_email, dl_cb, cmd) + tdcli_function ({ + ID = "SetRecoveryEmail", + password_ = password, + new_recovery_email_ = new_recovery_email + }, dl_cb, cmd) +end + +M.setRecoveryEmail = setRecoveryEmail + +-- Requests to send password recovery code to email +local function requestPasswordRecovery(dl_cb, cmd) + tdcli_function ({ + ID = "RequestPasswordRecovery", + }, dl_cb, cmd) +end + +M.requestPasswordRecovery = requestPasswordRecovery + +-- Recovers password with recovery code sent to email +-- @recovery_code Recovery code to check +local function recoverPassword(recovery_code, dl_cb, cmd) + tdcli_function ({ + ID = "RecoverPassword", + recovery_code_ = tostring(recovery_code) + }, dl_cb, cmd) +end + +M.recoverPassword = recoverPassword + +-- Returns current logged in user +local function getMe(dl_cb, cmd) + tdcli_function ({ + ID = "GetMe", + }, dl_cb, cmd) +end + +M.getMe = getMe + +-- Returns information about a user by its identifier, offline request if current user is not a bot +-- @user_id User identifier +local function getUser(user_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetUser", + user_id_ = user_id + }, dl_cb, cmd) +end + +M.getUser = getUser + +-- Returns full information about a user by its identifier +-- @user_id User identifier +local function getUserFull(user_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetUserFull", + user_id_ = user_id + }, dl_cb, cmd) +end + +M.getUserFull = getUserFull + +-- Returns information about a group by its identifier, offline request if current user is not a bot +-- @group_id Group identifier +local function getGroup(group_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetGroup", + group_id_ = getChatId(group_id).ID + }, dl_cb, cmd) +end + +M.getGroup = getGroup + +-- Returns full information about a group by its identifier +-- @group_id Group identifier +local function getGroupFull(group_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetGroupFull", + group_id_ = getChatId(group_id).ID + }, dl_cb, cmd) +end + +M.getGroupFull = getGroupFull + +-- Returns information about a channel by its identifier, offline request if current user is not a bot +-- @channel_id Channel identifier +local function getChannel(channel_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetChannel", + channel_id_ = getChatId(channel_id).ID + }, dl_cb, cmd) +end + +M.getChannel = getChannel + +-- Returns full information about a channel by its identifier, cached for at most 1 minute +-- @channel_id Channel identifier +local function getChannelFull(channel_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetChannelFull", + channel_id_ = getChatId(channel_id).ID + }, dl_cb, cmd) +end + +M.getChannelFull = getChannelFull + +-- Returns information about a secret chat by its identifier, offline request +-- @secret_chat_id Secret chat identifier +local function getSecretChat(secret_chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetSecretChat", + secret_chat_id_ = secret_chat_id + }, dl_cb, cmd) +end + +M.getSecretChat = getSecretChat + +-- Returns information about a chat by its identifier, offline request if current user is not a bot +-- @chat_id Chat identifier +local function getChat(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetChat", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.getChat = getChat + +-- Returns information about a message +-- @chat_id Identifier of the chat, message belongs to +-- @message_id Identifier of the message to get +local function getMessage(chat_id, message_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetMessage", + chat_id_ = chat_id, + message_id_ = message_id + }, dl_cb, cmd) +end + +M.getMessage = getMessage + +-- Returns information about messages. +-- If message is not found, returns null on the corresponding position of the result +-- @chat_id Identifier of the chat, messages belongs to +-- @message_ids Identifiers of the messages to get +local function getMessages(chat_id, message_ids, dl_cb, cmd) + tdcli_function ({ + ID = "GetMessages", + chat_id_ = chat_id, + message_ids_ = message_ids -- vector + }, dl_cb, cmd) +end + +M.getMessages = getMessages + +-- Returns information about a file, offline request +-- @file_id Identifier of the file to get +local function getFile(file_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetFile", + file_id_ = file_id + }, dl_cb, cmd) +end + +M.getFile = getFile + +-- Returns information about a file by its persistent id, offline request +-- @persistent_file_id Persistent identifier of the file to get +local function getFilePersistent(persistent_file_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetFilePersistent", + persistent_file_id_ = persistent_file_id + }, dl_cb, cmd) +end + +M.getFilePersistent = getFilePersistent + +-- Returns list of chats in the right order, chats are sorted by (order, chat_id) in decreasing order. +-- For example, to get list of chats from the beginning, the offset_order should be equal 2^63 - 1 +-- @offset_order Chat order to return chats from +-- @offset_chat_id Chat identifier to return chats from +-- @limit Maximum number of chats to be returned +local function getChats(offset_order, offset_chat_id, limit, dl_cb, cmd) + if not limit or limit > 20 then + limit = 20 + end + + tdcli_function ({ + ID = "GetChats", + offset_order_ = offset_order or 9223372036854775807, + offset_chat_id_ = offset_chat_id or 0, + limit_ = limit + }, dl_cb, cmd) +end + +M.getChats = getChats + +-- Searches public chat by its username. +-- Currently only private and channel chats can be public. +-- Returns chat if found, otherwise some error is returned +-- @username Username to be resolved +local function searchPublicChat(username, dl_cb, cmd) + tdcli_function ({ + ID = "SearchPublicChat", + username_ = username + }, dl_cb, cmd) +end + +M.searchPublicChat = searchPublicChat + +-- Searches public chats by prefix of their username. +-- Currently only private and channel (including supergroup) chats can be public. +-- Returns meaningful number of results. +-- Returns nothing if length of the searched username prefix is less than 5. +-- Excludes private chats with contacts from the results +-- @username_prefix Prefix of the username to search +local function searchPublicChats(username_prefix, dl_cb, cmd) + tdcli_function ({ + ID = "SearchPublicChats", + username_prefix_ = username_prefix + }, dl_cb, cmd) +end + +M.searchPublicChats = searchPublicChats + +-- Searches for specified query in the title and username of known chats, offline request. +-- Returns chats in the order of them in the chat list +-- @query Query to search for, if query is empty, returns up to 20 recently found chats +-- @limit Maximum number of chats to be returned +local function searchChats(query, limit, dl_cb, cmd) + if not limit or limit > 20 then + limit = 20 + end + + tdcli_function ({ + ID = "SearchChats", + query_ = query, + limit_ = limit + }, dl_cb, cmd) +end + +M.searchChats = searchChats + +-- Adds chat to the list of recently found chats. +-- The chat is added to the beginning of the list. +-- If the chat is already in the list, at first it is removed from the list +-- @chat_id Identifier of the chat to add +local function addRecentlyFoundChat(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "AddRecentlyFoundChat", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.addRecentlyFoundChat = addRecentlyFoundChat + +-- Deletes chat from the list of recently found chats +-- @chat_id Identifier of the chat to delete +local function deleteRecentlyFoundChat(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteRecentlyFoundChat", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.deleteRecentlyFoundChat = deleteRecentlyFoundChat + +-- Clears list of recently found chats +local function deleteRecentlyFoundChats(dl_cb, cmd) + tdcli_function ({ + ID = "DeleteRecentlyFoundChats", + }, dl_cb, cmd) +end + +M.deleteRecentlyFoundChats = deleteRecentlyFoundChats + +-- Returns list of common chats with an other given user. +-- Chats are sorted by their type and creation date +-- @user_id User identifier +-- @offset_chat_id Chat identifier to return chats from, use 0 for the first request +-- @limit Maximum number of chats to be returned, up to 100 +local function getCommonChats(user_id, offset_chat_id, limit, dl_cb, cmd) + if not limit or limit > 100 then + limit = 100 + end + + tdcli_function ({ + ID = "GetCommonChats", + user_id_ = user_id, + offset_chat_id_ = offset_chat_id, + limit_ = limit + }, dl_cb, cmd) +end + +M.getCommonChats = getCommonChats + +-- Returns messages in a chat. +-- Automatically calls openChat. +-- Returns result in reverse chronological order, i.e. in order of decreasing message.message_id +-- @chat_id Chat identifier +-- @from_message_id Identifier of the message near which we need a history, you can use 0 to get results from the beginning, i.e. from oldest to newest +-- @offset Specify 0 to get results exactly from from_message_id or negative offset to get specified message and some newer messages +-- @limit Maximum number of messages to be returned, should be positive and can't be greater than 100. +-- If offset is negative, limit must be greater than -offset. +-- There may be less than limit messages returned even the end of the history is not reached +local function getChatHistory(chat_id, from_message_id, offset, limit, dl_cb, cmd) + if not limit or limit > 100 then + limit = 100 + end + + tdcli_function ({ + ID = "GetChatHistory", + chat_id_ = chat_id, + from_message_id_ = from_message_id, + offset_ = offset or 0, + limit_ = limit + }, dl_cb, cmd) +end + +M.getChatHistory = getChatHistory + +-- Deletes all messages in the chat. +-- Can't be used for channel chats +-- @chat_id Chat identifier +-- @remove_from_chat_list Pass true, if chat should be removed from the chat list +local function deleteChatHistory(chat_id, remove_from_chat_list, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteChatHistory", + chat_id_ = chat_id, + remove_from_chat_list_ = remove_from_chat_list + }, dl_cb, cmd) +end + +M.deleteChatHistory = deleteChatHistory + +-- Searches for messages with given words in the chat. +-- Returns result in reverse chronological order, i. e. in order of decreasimg message_id. +-- Doesn't work in secret chats +-- @chat_id Chat identifier to search in +-- @query Query to search for +-- @from_message_id Identifier of the message from which we need a history, you can use 0 to get results from beginning +-- @limit Maximum number of messages to be returned, can't be greater than 100 +-- @filter Filter for content of searched messages +-- filter = Empty|Animation|Audio|Document|Photo|Video|Voice|PhotoAndVideo|Url|ChatPhoto +local function searchChatMessages(chat_id, query, from_message_id, limit, filter, dl_cb, cmd) + if not limit or limit > 100 then + limit = 100 + end + + tdcli_function ({ + ID = "SearchChatMessages", + chat_id_ = chat_id, + query_ = query, + from_message_id_ = from_message_id, + limit_ = limit, + filter_ = { + ID = 'SearchMessagesFilter' .. filter + }, + }, dl_cb, cmd) +end + +M.searchChatMessages = searchChatMessages + +-- Searches for messages in all chats except secret chats. Returns result in reverse chronological order, i. e. in order of decreasing (date, chat_id, message_id) +-- @query Query to search for +-- @offset_date Date of the message to search from, you can use 0 or any date in the future to get results from the beginning +-- @offset_chat_id Chat identifier of the last found message or 0 for the first request +-- @offset_message_id Message identifier of the last found message or 0 for the first request +-- @limit Maximum number of messages to be returned, can't be greater than 100 +local function searchMessages(query, offset_date, offset_chat_id, offset_message_id, limit, dl_cb, cmd) + if not limit or limit > 100 then + limit = 100 + end + + tdcli_function ({ + ID = "SearchMessages", + query_ = query, + offset_date_ = offset_date, + offset_chat_id_ = offset_chat_id, + offset_message_id_ = offset_message_id, + limit_ = limit + }, dl_cb, cmd) +end + +M.searchMessages = searchMessages + +-- Invites bot to a chat (if it is not in the chat) and send /start to it. +-- Bot can't be invited to a private chat other than chat with the bot. +-- Bots can't be invited to broadcast channel chats and secret chats. +-- Returns sent message. +-- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message +-- @bot_user_id Identifier of the bot +-- @chat_id Identifier of the chat +-- @parameter Hidden parameter sent to bot for deep linking (https://api.telegram.org/bots#deep-linking) +-- parameter=start|startgroup or custom as defined by bot creator +local function sendBotStartMessage(bot_user_id, chat_id, parameter, dl_cb, cmd) + tdcli_function ({ + ID = "SendBotStartMessage", + bot_user_id_ = bot_user_id, + chat_id_ = chat_id, + parameter_ = parameter + }, dl_cb, cmd) +end + +M.sendBotStartMessage = sendBotStartMessage + +-- Sends result of the inline query as a message. +-- Returns sent message. +-- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message. +-- Always clears chat draft message +-- @chat_id Chat to send message +-- @reply_to_message_id Identifier of a message to reply to or 0 +-- @disable_notification Pass true, to disable notification about the message, doesn't works in secret chats +-- @from_background Pass true, if the message is sent from background +-- @query_id Identifier of the inline query +-- @result_id Identifier of the inline result +local function sendInlineQueryResultMessage(chat_id, reply_to_message_id, disable_notification, from_background, query_id, result_id, dl_cb, cmd) + tdcli_function ({ + ID = "SendInlineQueryResultMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + query_id_ = query_id, + result_id_ = result_id + }, dl_cb, cmd) +end + +M.sendInlineQueryResultMessage = sendInlineQueryResultMessage + +-- Forwards previously sent messages. +-- Returns forwarded messages in the same order as message identifiers passed in message_ids. +-- If message can't be forwarded, null will be returned instead of the message. +-- UpdateChatTopMessage will not be sent, so returned messages should be used to update chat top message +-- @chat_id Identifier of a chat to forward messages +-- @from_chat_id Identifier of a chat to forward from +-- @message_ids Identifiers of messages to forward +-- @disable_notification Pass true, to disable notification about the message, doesn't works if messages are forwarded to secret chat +-- @from_background Pass true, if the message is sent from background +local function forwardMessages(chat_id, from_chat_id, message_ids, disable_notification, dl_cb, cmd) + tdcli_function ({ + ID = "ForwardMessages", + chat_id_ = chat_id, + from_chat_id_ = from_chat_id, + message_ids_ = message_ids, -- vector + disable_notification_ = disable_notification, + from_background_ = 1 + }, dl_cb, cmd) +end + +M.forwardMessages = forwardMessages + +-- Changes current ttl setting in a secret chat and sends corresponding message +-- @chat_id Chat identifier +-- @ttl New value of ttl in seconds +local function sendChatSetTtlMessage(chat_id, ttl, dl_cb, cmd) + tdcli_function ({ + ID = "SendChatSetTtlMessage", + chat_id_ = chat_id, + ttl_ = ttl + }, dl_cb, cmd) +end + +M.sendChatSetTtlMessage = sendChatSetTtlMessage + +-- Deletes messages. +-- UpdateDeleteMessages will not be sent for messages deleted through that function +-- @chat_id Chat identifier +-- @message_ids Identifiers of messages to delete +local function deleteMessages(chat_id, message_ids, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteMessages", + chat_id_ = chat_id, + message_ids_ = message_ids -- vector + }, dl_cb, cmd) +end + +M.deleteMessages = deleteMessages + +-- Deletes all messages in the chat sent by the specified user. +-- Works only in supergroup channel chats, needs appropriate privileges +-- @chat_id Chat identifier +-- @user_id User identifier +local function deleteMessagesFromUser(chat_id, user_id, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteMessagesFromUser", + chat_id_ = chat_id, + user_id_ = user_id + }, dl_cb, cmd) +end + +M.deleteMessagesFromUser = deleteMessagesFromUser + +-- Edits text of text or game message. +-- Non-bots can edit message in a limited period of time. +-- Returns edited message after edit is complete server side +-- @chat_id Chat the message belongs to +-- @message_id Identifier of the message +-- @reply_markup Bots only. New message reply markup +-- @input_message_content New text content of the message. Should be of type InputMessageText +local function editMessageText(chat_id, message_id, reply_markup, text, disable_web_page_preview, parse_mode, dl_cb, cmd) + local TextParseMode = getParseMode(parse_mode) + + tdcli_function ({ + ID = "EditMessageText", + chat_id_ = chat_id, + message_id_ = message_id, + reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup + input_message_content_ = { + ID = "InputMessageText", + text_ = text, + disable_web_page_preview_ = disable_web_page_preview, + clear_draft_ = 0, + entities_ = {}, + parse_mode_ = TextParseMode, + }, + }, dl_cb, cmd) +end + +M.editMessageText = editMessageText + +-- Edits message content caption. +-- Non-bots can edit message in a limited period of time. +-- Returns edited message after edit is complete server side +-- @chat_id Chat the message belongs to +-- @message_id Identifier of the message +-- @reply_markup Bots only. New message reply markup +-- @caption New message content caption, 0-200 characters +local function editMessageCaption(chat_id, message_id, reply_markup, caption, dl_cb, cmd) + tdcli_function ({ + ID = "EditMessageCaption", + chat_id_ = chat_id, + message_id_ = message_id, + reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup + caption_ = caption + }, dl_cb, cmd) +end + +M.editMessageCaption = editMessageCaption + +-- Bots only. +-- Edits message reply markup. +-- Returns edited message after edit is complete server side +-- @chat_id Chat the message belongs to +-- @message_id Identifier of the message +-- @reply_markup New message reply markup +local function editMessageReplyMarkup(inline_message_id, reply_markup, caption, dl_cb, cmd) + tdcli_function ({ + ID = "EditInlineMessageCaption", + inline_message_id_ = inline_message_id, + reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup + caption_ = caption + }, dl_cb, cmd) +end + +M.editMessageReplyMarkup = editMessageReplyMarkup + +-- Bots only. +-- Edits text of an inline text or game message sent via bot +-- @inline_message_id Inline message identifier +-- @reply_markup New message reply markup +-- @input_message_content New text content of the message. Should be of type InputMessageText +local function editInlineMessageText(inline_message_id, reply_markup, text, disable_web_page_preview, dl_cb, cmd) + tdcli_function ({ + ID = "EditInlineMessageText", + inline_message_id_ = inline_message_id, + reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup + input_message_content_ = { + ID = "InputMessageText", + text_ = text, + disable_web_page_preview_ = disable_web_page_preview, + clear_draft_ = 0, + entities_ = {} + }, + }, dl_cb, cmd) +end + +M.editInlineMessageText = editInlineMessageText + +-- Bots only. +-- Edits caption of an inline message content sent via bot +-- @inline_message_id Inline message identifier +-- @reply_markup New message reply markup +-- @caption New message content caption, 0-200 characters +local function editInlineMessageCaption(inline_message_id, reply_markup, caption, dl_cb, cmd) + tdcli_function ({ + ID = "EditInlineMessageCaption", + inline_message_id_ = inline_message_id, + reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup + caption_ = caption + }, dl_cb, cmd) +end + +M.editInlineMessageCaption = editInlineMessageCaption + +-- Bots only. +-- Edits reply markup of an inline message sent via bot +-- @inline_message_id Inline message identifier +-- @reply_markup New message reply markup +local function editInlineMessageReplyMarkup(inline_message_id, reply_markup, dl_cb, cmd) + tdcli_function ({ + ID = "EditInlineMessageReplyMarkup", + inline_message_id_ = inline_message_id, + reply_markup_ = reply_markup -- reply_markup:ReplyMarkup + }, dl_cb, cmd) +end + +M.editInlineMessageReplyMarkup = editInlineMessageReplyMarkup + + +-- Sends inline query to a bot and returns its results. +-- Unavailable for bots +-- @bot_user_id Identifier of the bot send query to +-- @chat_id Identifier of the chat, where the query is sent +-- @user_location User location, only if needed +-- @query Text of the query +-- @offset Offset of the first entry to return +local function getInlineQueryResults(bot_user_id, chat_id, latitude, longitude, query, offset, dl_cb, cmd) + tdcli_function ({ + ID = "GetInlineQueryResults", + bot_user_id_ = bot_user_id, + chat_id_ = chat_id, + user_location_ = { + ID = "Location", + latitude_ = latitude, + longitude_ = longitude + }, + query_ = query, + offset_ = offset + }, dl_cb, cmd) +end + +M.getInlineQueryResults = getInlineQueryResults + +-- Bots only. +-- Sets result of the inline query +-- @inline_query_id Identifier of the inline query +-- @is_personal Does result of the query can be cached only for specified user +-- @results Results of the query +-- @cache_time Allowed time to cache results of the query in seconds +-- @next_offset Offset for the next inline query, pass empty string if there is no more results +-- @switch_pm_text If non-empty, this text should be shown on the button, which opens private chat with the bot and sends bot start message with parameter switch_pm_parameter +-- @switch_pm_parameter Parameter for the bot start message +local function answerInlineQuery(inline_query_id, is_personal, cache_time, next_offset, switch_pm_text, switch_pm_parameter, dl_cb, cmd) + tdcli_function ({ + ID = "AnswerInlineQuery", + inline_query_id_ = inline_query_id, + is_personal_ = is_personal, + results_ = results, --vector<InputInlineQueryResult>, + cache_time_ = cache_time, + next_offset_ = next_offset, + switch_pm_text_ = switch_pm_text, + switch_pm_parameter_ = switch_pm_parameter + }, dl_cb, cmd) +end + +M.answerInlineQuery = answerInlineQuery + +-- Sends callback query to a bot and returns answer to it. +-- Unavailable for bots +-- @chat_id Identifier of the chat with a message +-- @message_id Identifier of the message, from which the query is originated +-- @payload Query payload +-- @text Text of the answer +-- @show_alert If true, an alert should be shown to the user instead of a toast +-- @url URL to be open +local function getCallbackQueryAnswer(chat_id, message_id, text, show_alert, url, dl_cb, cmd) + tdcli_function ({ + ID = "GetCallbackQueryAnswer", + chat_id_ = chat_id, + message_id_ = message_id, + payload_ = { + ID = "CallbackQueryAnswer", + text_ = text, + show_alert_ = show_alert, + url_ = url + }, + }, dl_cb, cmd) +end + +M.getCallbackQueryAnswer = getCallbackQueryAnswer + +-- Bots only. +-- Sets result of the callback query +-- @callback_query_id Identifier of the callback query +-- @text Text of the answer +-- @show_alert If true, an alert should be shown to the user instead of a toast +-- @url Url to be opened +-- @cache_time Allowed time to cache result of the query in seconds +local function answerCallbackQuery(callback_query_id, text, show_alert, url, cache_time, dl_cb, cmd) + tdcli_function ({ + ID = "AnswerCallbackQuery", + callback_query_id_ = callback_query_id, + text_ = text, + show_alert_ = show_alert, + url_ = url, + cache_time_ = cache_time + }, dl_cb, cmd) +end + +M.answerCallbackQuery = answerCallbackQuery + +-- Bots only. +-- Updates game score of the specified user in the game +-- @chat_id Chat a message with the game belongs to +-- @message_id Identifier of the message +-- @edit_message True, if message should be edited +-- @user_id User identifier +-- @score New score +-- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table +local function setGameScore(chat_id, message_id, edit_message, user_id, score, force, dl_cb, cmd) + tdcli_function ({ + ID = "SetGameScore", + chat_id_ = chat_id, + message_id_ = message_id, + edit_message_ = edit_message, + user_id_ = user_id, + score_ = score, + force_ = force + }, dl_cb, cmd) +end + +M.setGameScore = setGameScore + +-- Bots only. +-- Updates game score of the specified user in the game +-- @inline_message_id Inline message identifier +-- @edit_message True, if message should be edited +-- @user_id User identifier +-- @score New score +-- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table +local function setInlineGameScore(inline_message_id, edit_message, user_id, score, force, dl_cb, cmd) + tdcli_function ({ + ID = "SetInlineGameScore", + inline_message_id_ = inline_message_id, + edit_message_ = edit_message, + user_id_ = user_id, + score_ = score, + force_ = force + }, dl_cb, cmd) +end + +M.setInlineGameScore = setInlineGameScore + +-- Bots only. +-- Returns game high scores and some part of the score table around of the specified user in the game +-- @chat_id Chat a message with the game belongs to +-- @message_id Identifier of the message +-- @user_id User identifie +local function getGameHighScores(chat_id, message_id, user_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetGameHighScores", + chat_id_ = chat_id, + message_id_ = message_id, + user_id_ = user_id + }, dl_cb, cmd) +end + +M.getGameHighScores = getGameHighScores + +-- Bots only. +-- Returns game high scores and some part of the score table around of the specified user in the game +-- @inline_message_id Inline message identifier +-- @user_id User identifier +local function getInlineGameHighScores(inline_message_id, user_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetInlineGameHighScores", + inline_message_id_ = inline_message_id, + user_id_ = user_id + }, dl_cb, cmd) +end + +M.getInlineGameHighScores = getInlineGameHighScores + +-- Deletes default reply markup from chat. +-- This method needs to be called after one-time keyboard or ForceReply reply markup has been used. +-- UpdateChatReplyMarkup will be send if reply markup will be changed +-- @chat_id Chat identifier +-- @message_id Message identifier of used keyboard +local function deleteChatReplyMarkup(chat_id, message_id, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteChatReplyMarkup", + chat_id_ = chat_id, + message_id_ = message_id + }, dl_cb, cmd) +end + +M.deleteChatReplyMarkup = deleteChatReplyMarkup + +-- Sends notification about user activity in a chat +-- @chat_id Chat identifier +-- @action Action description +-- action = Typing|Cancel|RecordVideo|UploadVideo|RecordVoice|UploadVoice|UploadPhoto|UploadDocument|GeoLocation|ChooseContact|StartPlayGame +local function sendChatAction(chat_id, action, progress, dl_cb, cmd) + tdcli_function ({ + ID = "SendChatAction", + chat_id_ = chat_id, + action_ = { + ID = "SendMessage" .. action .. "Action", + progress_ = progress or 100 + } + }, dl_cb, cmd) +end + +M.sendChatAction = sendChatAction + +-- Sends notification about screenshot taken in a chat. +-- Works only in secret chats +-- @chat_id Chat identifier +local function sendChatScreenshotTakenNotification(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "SendChatScreenshotTakenNotification", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.sendChatScreenshotTakenNotification = sendChatScreenshotTakenNotification + +-- Chat is opened by the user. +-- Many useful activities depends on chat being opened or closed. For example, in channels all updates are received only for opened chats +-- @chat_id Chat identifier +local function openChat(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "OpenChat", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.openChat = openChat + +-- Chat is closed by the user. +-- Many useful activities depends on chat being opened or closed. +-- @chat_id Chat identifier +local function closeChat(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "CloseChat", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.closeChat = closeChat + +-- Messages are viewed by the user. +-- Many useful activities depends on message being viewed. For example, marking messages as read, incrementing of view counter, updating of view counter, removing of deleted messages in channels +-- @chat_id Chat identifier +-- @message_ids Identifiers of viewed messages +local function viewMessages(chat_id, message_ids, dl_cb, cmd) + tdcli_function ({ + ID = "ViewMessages", + chat_id_ = chat_id, + message_ids_ = message_ids -- vector + }, dl_cb, cmd) +end + +M.viewMessages = viewMessages + +-- Message content is opened, for example the user has opened a photo, a video, a document, a location or a venue or have listened to an audio or a voice message +-- @chat_id Chat identifier of the message +-- @message_id Identifier of the message with opened content +local function openMessageContent(chat_id, message_id, dl_cb, cmd) + tdcli_function ({ + ID = "OpenMessageContent", + chat_id_ = chat_id, + message_id_ = message_id + }, dl_cb, cmd) +end + +M.openMessageContent = openMessageContent + +-- Returns existing chat corresponding to the given user +-- @user_id User identifier +local function createPrivateChat(user_id, dl_cb, cmd) + tdcli_function ({ + ID = "CreatePrivateChat", + user_id_ = user_id + }, dl_cb, cmd) +end + +M.createPrivateChat = createPrivateChat + +-- Returns existing chat corresponding to the known group +-- @group_id Group identifier +local function createGroupChat(group_id, dl_cb, cmd) + tdcli_function ({ + ID = "CreateGroupChat", + group_id_ = getChatId(group_id).ID + }, dl_cb, cmd) +end + +M.createGroupChat = createGroupChat + +-- Returns existing chat corresponding to the known channel +-- @channel_id Channel identifier +local function createChannelChat(channel_id, dl_cb, cmd) + tdcli_function ({ + ID = "CreateChannelChat", + channel_id_ = getChatId(channel_id).ID + }, dl_cb, cmd) +end + +M.createChannelChat = createChannelChat + +-- Returns existing chat corresponding to the known secret chat +-- @secret_chat_id SecretChat identifier +local function createSecretChat(secret_chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "CreateSecretChat", + secret_chat_id_ = secret_chat_id + }, dl_cb, cmd) +end + +M.createSecretChat = createSecretChat + +-- Creates new group chat and send corresponding messageGroupChatCreate, returns created chat +-- @user_ids Identifiers of users to add to the group +-- @title Title of new group chat, 0-255 characters +local function createNewGroupChat(user_ids, title, dl_cb, cmd) + tdcli_function ({ + ID = "CreateNewGroupChat", + user_ids_ = user_ids, -- vector + title_ = title + }, dl_cb, cmd) +end + +M.createNewGroupChat = createNewGroupChat + +-- Creates new channel chat and send corresponding messageChannelChatCreate, returns created chat +-- @title Title of new channel chat, 0-255 characters +-- @is_supergroup True, if supergroup chat should be created +-- @about Information about the channel, 0-255 characters +local function createNewChannelChat(title, is_supergroup, about, dl_cb, cmd) + tdcli_function ({ + ID = "CreateNewChannelChat", + title_ = title, + is_supergroup_ = is_supergroup, + about_ = about + }, dl_cb, cmd) +end + +M.createNewChannelChat = createNewChannelChat + +-- Creates new secret chat, returns created chat +-- @user_id Identifier of a user to create secret chat with +local function createNewSecretChat(user_id, dl_cb, cmd) + tdcli_function ({ + ID = "CreateNewSecretChat", + user_id_ = user_id + }, dl_cb, cmd) +end + +M.createNewSecretChat = createNewSecretChat + +-- Creates new channel supergroup chat from existing group chat and send corresponding messageChatMigrateTo and messageChatMigrateFrom. Deactivates group +-- @chat_id Group chat identifier +local function migrateGroupChatToChannelChat(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "MigrateGroupChatToChannelChat", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.migrateGroupChatToChannelChat = migrateGroupChatToChannelChat + +-- Changes chat title. +-- Title can't be changed for private chats. +-- Title will not change until change will be synchronized with the server. +-- Title will not be changed if application is killed before it can send request to the server. +-- There will be update about change of the title on success. Otherwise error will be returned +-- @chat_id Chat identifier +-- @title New title of a chat, 0-255 characters +local function changeChatTitle(chat_id, title, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeChatTitle", + chat_id_ = chat_id, + title_ = title + }, dl_cb, cmd) +end + +M.changeChatTitle = changeChatTitle + +-- Changes chat photo. +-- Photo can't be changed for private chats. +-- Photo will not change until change will be synchronized with the server. +-- Photo will not be changed if application is killed before it can send request to the server. +-- There will be update about change of the photo on success. Otherwise error will be returned +-- @chat_id Chat identifier +-- @photo New chat photo. You can use zero InputFileId to delete photo. Files accessible only by HTTP URL are not acceptable +local function changeChatPhoto(chat_id, photo, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeChatPhoto", + chat_id_ = chat_id, + photo_ = getInputFile(photo) + }, dl_cb, cmd) +end + +M.changeChatPhoto = changeChatPhoto + +-- Changes chat draft message +-- @chat_id Chat identifier +-- @draft_message New draft message, nullable +local function changeChatDraftMessage(chat_id, reply_to_message_id, text, disable_web_page_preview, clear_draft, parse_mode, dl_cb, cmd) + local TextParseMode = getParseMode(parse_mode) + + tdcli_function ({ + ID = "ChangeChatDraftMessage", + chat_id_ = chat_id, + draft_message_ = { + ID = "DraftMessage", + reply_to_message_id_ = reply_to_message_id, + input_message_text_ = { + ID = "InputMessageText", + text_ = text, + disable_web_page_preview_ = disable_web_page_preview, + clear_draft_ = clear_draft, + entities_ = {}, + parse_mode_ = TextParseMode, + }, + }, + }, dl_cb, cmd) +end + +M.changeChatDraftMessage = changeChatDraftMessage + +-- Adds new member to chat. +-- Members can't be added to private or secret chats. +-- Member will not be added until chat state will be synchronized with the server. +-- Member will not be added if application is killed before it can send request to the server +-- @chat_id Chat identifier +-- @user_id Identifier of the user to add +-- @forward_limit Number of previous messages from chat to forward to new member, ignored for channel chats +local function addChatMember(chat_id, user_id, forward_limit, dl_cb, cmd) + tdcli_function ({ + ID = "AddChatMember", + chat_id_ = chat_id, + user_id_ = user_id, + forward_limit_ = forward_limit or 50 + }, dl_cb, cmd) +end + +M.addChatMember = addChatMember + +-- Adds many new members to the chat. +-- Currently, available only for channels. +-- Can't be used to join the channel. +-- Member will not be added until chat state will be synchronized with the server. +-- Member will not be added if application is killed before it can send request to the server +-- @chat_id Chat identifier +-- @user_ids Identifiers of the users to add +local function addChatMembers(chat_id, user_ids, dl_cb, cmd) + tdcli_function ({ + ID = "AddChatMembers", + chat_id_ = chat_id, + user_ids_ = user_ids -- vector + }, dl_cb, cmd) +end + +M.addChatMembers = addChatMembers + +-- Changes status of the chat member, need appropriate privileges. +-- In channel chats, user will be added to chat members if he is yet not a member and there is less than 200 members in the channel. +-- Status will not be changed until chat state will be synchronized with the server. +-- Status will not be changed if application is killed before it can send request to the server +-- @chat_id Chat identifier +-- @user_id Identifier of the user to edit status, bots can be editors in the channel chats +-- @status New status of the member in the chat +-- status = Creator|Editor|Moderator|Member|Left|Kicked +local function changeChatMemberStatus(chat_id, user_id, status, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeChatMemberStatus", + chat_id_ = chat_id, + user_id_ = user_id, + status_ = { + ID = "ChatMemberStatus" .. status + }, + }, dl_cb, cmd) +end + +M.changeChatMemberStatus = changeChatMemberStatus + +-- Returns information about one participant of the chat +-- @chat_id Chat identifier +-- @user_id User identifier +local function getChatMember(chat_id, user_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetChatMember", + chat_id_ = chat_id, + user_id_ = user_id + }, dl_cb, cmd) +end + +M.getChatMember = getChatMember + +-- Asynchronously downloads file from cloud. +-- Updates updateFileProgress will notify about download progress. +-- Update updateFile will notify about successful download +-- @file_id Identifier of file to download +local function downloadFile(file_id, dl_cb, cmd) + tdcli_function ({ + ID = "DownloadFile", + file_id_ = file_id + }, dl_cb, cmd) +end + +M.downloadFile = downloadFile + +-- Stops file downloading. +-- If file already downloaded do nothing. +-- @file_id Identifier of file to cancel download +local function cancelDownloadFile(file_id, dl_cb, cmd) + tdcli_function ({ + ID = "CancelDownloadFile", + file_id_ = file_id + }, dl_cb, cmd) +end + +M.cancelDownloadFile = cancelDownloadFile + +-- Next part of a file was generated +-- @generation_id Identifier of the generation process +-- @ready Number of bytes already generated. Negative number means that generation has failed and should be terminated +local function setFileGenerationProgress(generation_id, ready, dl_cb, cmd) + tdcli_function ({ + ID = "SetFileGenerationProgress", + generation_id_ = generation_id, + ready_ = ready + }, dl_cb, cmd) +end + +M.setFileGenerationProgress = setFileGenerationProgress + +-- Finishes file generation +-- @generation_id Identifier of the generation process +local function finishFileGeneration(generation_id, dl_cb, cmd) + tdcli_function ({ + ID = "FinishFileGeneration", + generation_id_ = generation_id + }, dl_cb, cmd) +end + +M.finishFileGeneration = finishFileGeneration + +-- Generates new chat invite link, previously generated link is revoked. +-- Available for group and channel chats. +-- Only creator of the chat can export chat invite link +-- @chat_id Chat identifier +local function exportChatInviteLink(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "ExportChatInviteLink", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.exportChatInviteLink = exportChatInviteLink + +-- Checks chat invite link for validness and returns information about the corresponding chat +-- @invite_link Invite link to check. Should begin with "https://telegram.me/joinchat/" +local function checkChatInviteLink(link, dl_cb, cmd) + tdcli_function ({ + ID = "CheckChatInviteLink", + invite_link_ = link + }, dl_cb, cmd) +end + +M.checkChatInviteLink = checkChatInviteLink + +-- Imports chat invite link, adds current user to a chat if possible. +-- Member will not be added until chat state will be synchronized with the server. +-- Member will not be added if application is killed before it can send request to the server +-- @invite_link Invite link to import. Should begin with "https://telegram.me/joinchat/" +local function importChatInviteLink(invite_link, dl_cb, cmd) + tdcli_function ({ + ID = "ImportChatInviteLink", + invite_link_ = invite_link + }, dl_cb, cmd) +end + +M.importChatInviteLink = importChatInviteLink + +-- Adds user to black list +-- @user_id User identifier +local function blockUser(user_id, dl_cb, cmd) + tdcli_function ({ + ID = "BlockUser", + user_id_ = user_id + }, dl_cb, cmd) +end + +M.blockUser = blockUser + +-- Removes user from black list +-- @user_id User identifier +local function unblockUser(user_id, dl_cb, cmd) + tdcli_function ({ + ID = "UnblockUser", + user_id_ = user_id + }, dl_cb, cmd) +end + +M.unblockUser = unblockUser + +-- Returns users blocked by the current user +-- @offset Number of users to skip in result, must be non-negative +-- @limit Maximum number of users to return, can't be greater than 100 +local function getBlockedUsers(offset, limit, dl_cb, cmd) + tdcli_function ({ + ID = "GetBlockedUsers", + offset_ = offset, + limit_ = limit + }, dl_cb, cmd) +end + +M.getBlockedUsers = getBlockedUsers + +-- Adds new contacts/edits existing contacts, contacts user identifiers are ignored. +-- Returns list of corresponding users in the same order as input contacts. +-- If contact doesn't registered in Telegram, user with id == 0 will be returned +-- @contacts List of contacts to import/edit +local function importContacts(phone_number, first_name, last_name, user_id, dl_cb, cmd) + tdcli_function ({ + ID = "ImportContacts", + contacts_ = {[0] = { + phone_number_ = tostring(phone_number), + first_name_ = tostring(first_name), + last_name_ = tostring(last_name), + user_id_ = user_id + }, + }, + }, dl_cb, cmd) +end + +M.importContacts = importContacts + +-- Searches for specified query in the first name, last name and username of the known user contacts +-- @query Query to search for, can be empty to return all contacts +-- @limit Maximum number of users to be returned +local function searchContacts(query, limit, dl_cb, cmd) + tdcli_function ({ + ID = "SearchContacts", + query_ = query, + limit_ = limit + }, dl_cb, cmd) +end + +M.searchContacts = searchContacts + +-- Deletes users from contacts list +-- @user_ids Identifiers of users to be deleted +local function deleteContacts(user_ids, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteContacts", + user_ids_ = user_ids -- vector + }, dl_cb, cmd) +end + +M.deleteContacts = deleteContacts + +-- Returns profile photos of the user. +-- Result of this query can't be invalidated, so it must be used with care +-- @user_id User identifier +-- @offset Photos to skip, must be non-negative +-- @limit Maximum number of photos to be returned, can't be greater than 100 +local function getUserProfilePhotos(user_id, offset, limit, dl_cb, cmd) + tdcli_function ({ + ID = "GetUserProfilePhotos", + user_id_ = user_id, + offset_ = offset, + limit_ = limit + }, dl_cb, cmd) +end + +M.getUserProfilePhotos = getUserProfilePhotos + +-- Returns stickers corresponding to given emoji +-- @emoji String representation of emoji. If empty, returns all known stickers +local function getStickers(emoji, dl_cb, cmd) + tdcli_function ({ + ID = "GetStickers", + emoji_ = emoji + }, dl_cb, cmd) +end + +M.getStickers = getStickers + +-- Returns list of installed sticker sets without archived sticker sets +-- @is_masks Pass true to return masks, pass false to return stickers +local function getStickerSets(is_masks, dl_cb, cmd) + tdcli_function ({ + ID = "GetStickerSets", + is_masks_ = is_masks + }, dl_cb, cmd) +end + +M.getStickerSets = getStickerSets + +-- Returns list of archived sticker sets +-- @is_masks Pass true to return masks, pass false to return stickers +-- @offset_sticker_set_id Identifier of the sticker set from which return the result +-- @limit Maximum number of sticker sets to return +local function getArchivedStickerSets(is_masks, offset_sticker_set_id, limit, dl_cb, cmd) + tdcli_function ({ + ID = "GetArchivedStickerSets", + is_masks_ = is_masks, + offset_sticker_set_id_ = offset_sticker_set_id, + limit_ = limit + }, dl_cb, cmd) +end + +M.getArchivedStickerSets = getArchivedStickerSets + +-- Returns list of trending sticker sets +local function getTrendingStickerSets(dl_cb, cmd) + tdcli_function ({ + ID = "GetTrendingStickerSets" + }, dl_cb, cmd) +end + +M.getTrendingStickerSets = getTrendingStickerSets + +-- Returns list of sticker sets attached to a file, currently only photos and videos can have attached sticker sets +-- @file_id File identifier +local function getAttachedStickerSets(file_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetAttachedStickerSets", + file_id_ = file_id + }, dl_cb, cmd) +end + +M.getAttachedStickerSets = getAttachedStickerSets + +-- Returns information about sticker set by its identifier +-- @set_id Identifier of the sticker set +local function getStickerSet(set_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetStickerSet", + set_id_ = set_id + }, dl_cb, cmd) +end + +M.getStickerSet = getStickerSet + +-- Searches sticker set by its short name +-- @name Name of the sticker set +local function searchStickerSet(name, dl_cb, cmd) + tdcli_function ({ + ID = "SearchStickerSet", + name_ = name + }, dl_cb, cmd) +end + +M.searchStickerSet = searchStickerSet + +-- Installs/uninstalls or enables/archives sticker set. +-- Official sticker set can't be uninstalled, but it can be archived +-- @set_id Identifier of the sticker set +-- @is_installed New value of is_installed +-- @is_archived New value of is_archived +local function updateStickerSet(set_id, is_installed, is_archived, dl_cb, cmd) + tdcli_function ({ + ID = "UpdateStickerSet", + set_id_ = set_id, + is_installed_ = is_installed, + is_archived_ = is_archived + }, dl_cb, cmd) +end + +M.updateStickerSet = updateStickerSet + +-- Trending sticker sets are viewed by the user +-- @sticker_set_ids Identifiers of viewed trending sticker sets +local function viewTrendingStickerSets(sticker_set_ids, dl_cb, cmd) + tdcli_function ({ + ID = "ViewTrendingStickerSets", + sticker_set_ids_ = sticker_set_ids -- vector + }, dl_cb, cmd) +end + +M.viewTrendingStickerSets = viewTrendingStickerSets + +-- Changes the order of installed sticker sets +-- @is_masks Pass true to change masks order, pass false to change stickers order +-- @sticker_set_ids Identifiers of installed sticker sets in the new right order +local function reorderStickerSets(is_masks, sticker_set_ids, dl_cb, cmd) + tdcli_function ({ + ID = "ReorderStickerSets", + is_masks_ = is_masks, + sticker_set_ids_ = sticker_set_ids -- vector + }, dl_cb, cmd) +end + +M.reorderStickerSets = reorderStickerSets + +-- Returns list of recently used stickers +-- @is_attached Pass true to return stickers and masks recently attached to photo or video files, pass false to return recently sent stickers +local function getRecentStickers(is_attached, dl_cb, cmd) + tdcli_function ({ + ID = "GetRecentStickers", + is_attached_ = is_attached + }, dl_cb, cmd) +end + +M.getRecentStickers = getRecentStickers + +-- Manually adds new sticker to the list of recently used stickers. +-- New sticker is added to the beginning of the list. +-- If the sticker is already in the list, at first it is removed from the list +-- @is_attached Pass true to add the sticker to the list of stickers recently attached to photo or video files, pass false to add the sticker to the list of recently sent stickers +-- @sticker Sticker file to add +local function addRecentSticker(is_attached, sticker, dl_cb, cmd) + tdcli_function ({ + ID = "AddRecentSticker", + is_attached_ = is_attached, + sticker_ = getInputFile(sticker) + }, dl_cb, cmd) +end + +M.addRecentSticker = addRecentSticker + +-- Removes a sticker from the list of recently used stickers +-- @is_attached Pass true to remove the sticker from the list of stickers recently attached to photo or video files, pass false to remove the sticker from the list of recently sent stickers +-- @sticker Sticker file to delete +local function deleteRecentSticker(is_attached, sticker, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteRecentSticker", + is_attached_ = is_attached, + sticker_ = getInputFile(sticker) + }, dl_cb, cmd) +end + +M.deleteRecentSticker = deleteRecentSticker + +-- Clears list of recently used stickers +-- @is_attached Pass true to clear list of stickers recently attached to photo or video files, pass false to clear the list of recently sent stickers +local function clearRecentStickers(is_attached, dl_cb, cmd) + tdcli_function ({ + ID = "ClearRecentStickers", + is_attached_ = is_attached + }, dl_cb, cmd) +end + +M.clearRecentStickers = clearRecentStickers + +-- Returns emojis corresponding to a sticker +-- @sticker Sticker file identifier +local function getStickerEmojis(sticker, dl_cb, cmd) + tdcli_function ({ + ID = "GetStickerEmojis", + sticker_ = getInputFile(sticker) + }, dl_cb, cmd) +end + +M.getStickerEmojis = getStickerEmojis + +-- Returns saved animations +local function getSavedAnimations(dl_cb, cmd) + tdcli_function ({ + ID = "GetSavedAnimations", + }, dl_cb, cmd) +end + +M.getSavedAnimations = getSavedAnimations + +-- Manually adds new animation to the list of saved animations. +-- New animation is added to the beginning of the list. +-- If the animation is already in the list, at first it is removed from the list. +-- Only non-secret video animations with MIME type "video/mp4" can be added to the list +-- @animation Animation file to add. Only known to server animations (i. e. successfully sent via message) can be added to the list +local function addSavedAnimation(animation, dl_cb, cmd) + tdcli_function ({ + ID = "AddSavedAnimation", + animation_ = getInputFile(animation) + }, dl_cb, cmd) +end + +M.addSavedAnimation = addSavedAnimation + +-- Removes animation from the list of saved animations +-- @animation Animation file to delete +local function deleteSavedAnimation(animation, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteSavedAnimation", + animation_ = getInputFile(animation) + }, dl_cb, cmd) +end + +M.deleteSavedAnimation = deleteSavedAnimation + +-- Returns up to 20 recently used inline bots in the order of the last usage +local function getRecentInlineBots(dl_cb, cmd) + tdcli_function ({ + ID = "GetRecentInlineBots", + }, dl_cb, cmd) +end + +M.getRecentInlineBots = getRecentInlineBots + +-- Get web page preview by text of the message. +-- Do not call this function to often +-- @message_text Message text +local function getWebPagePreview(message_text, dl_cb, cmd) + tdcli_function ({ + ID = "GetWebPagePreview", + message_text_ = message_text + }, dl_cb, cmd) +end + +M.getWebPagePreview = getWebPagePreview + +-- Returns notification settings for a given scope +-- @scope Scope to return information about notification settings +-- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats| +local function getNotificationSettings(scope, chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetNotificationSettings", + scope_ = { + ID = 'NotificationSettingsFor' .. scope, + chat_id_ = chat_id or nil + }, + }, dl_cb, cmd) +end + +M.getNotificationSettings = getNotificationSettings + +-- Changes notification settings for a given scope +-- @scope Scope to change notification settings +-- @notification_settings New notification settings for given scope +-- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats| +local function setNotificationSettings(scope, chat_id, mute_for, show_preview, dl_cb, cmd) + tdcli_function ({ + ID = "SetNotificationSettings", + scope_ = { + ID = 'NotificationSettingsFor' .. scope, + chat_id_ = chat_id or nil + }, + notification_settings_ = { + ID = "NotificationSettings", + mute_for_ = mute_for, + sound_ = "default", + show_preview_ = show_preview + } + }, dl_cb, cmd) +end + +M.setNotificationSettings = setNotificationSettings + +-- Resets all notification settings to the default value. +-- By default the only muted chats are supergroups, sound is set to 'default' and message previews are showed +local function resetAllNotificationSettings(dl_cb, cmd) + tdcli_function ({ + ID = "ResetAllNotificationSettings" + }, dl_cb, cmd) +end + +M.resetAllNotificationSettings = resetAllNotificationSettings + +-- Uploads new profile photo for logged in user. +-- Photo will not change until change will be synchronized with the server. +-- Photo will not be changed if application is killed before it can send request to the server. +-- If something changes, updateUser will be sent +-- @photo_path Path to new profile photo +local function setProfilePhoto(photo_path, dl_cb, cmd) + tdcli_function ({ + ID = "SetProfilePhoto", + photo_path_ = photo_path + }, dl_cb, cmd) +end + +M.setProfilePhoto = setProfilePhoto + +-- Deletes profile photo. +-- If something changes, updateUser will be sent +-- @profile_photo_id Identifier of profile photo to delete +local function deleteProfilePhoto(profile_photo_id, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteProfilePhoto", + profile_photo_id_ = profile_photo_id + }, dl_cb, cmd) +end + +M.deleteProfilePhoto = deleteProfilePhoto + +-- Changes first and last names of logged in user. +-- If something changes, updateUser will be sent +-- @first_name New value of user first name, 1-255 characters +-- @last_name New value of optional user last name, 0-255 characters +local function changeName(first_name, last_name, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeName", + first_name_ = first_name, + last_name_ = last_name + }, dl_cb, cmd) +end + +M.changeName = changeName + +-- Changes about information of logged in user +-- @about New value of userFull.about, 0-255 characters +local function changeAbout(about, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeAbout", + about_ = about + }, dl_cb, cmd) +end + +M.changeAbout = changeAbout + +-- Changes username of logged in user. +-- If something changes, updateUser will be sent +-- @username New value of username. Use empty string to remove username +local function changeUsername(username, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeUsername", + username_ = username + }, dl_cb, cmd) +end + +M.changeUsername = changeUsername + +-- Changes user's phone number and sends authentication code to the new user's phone number. +-- Returns authStateWaitCode with information about sent code on success +-- @phone_number New user's phone number in any reasonable format +-- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number +-- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False +local function changePhoneNumber(phone_number, allow_flash_call, is_current_phone_number, dl_cb, cmd) + tdcli_function ({ + ID = "ChangePhoneNumber", + phone_number_ = phone_number, + allow_flash_call_ = allow_flash_call, + is_current_phone_number_ = is_current_phone_number + }, dl_cb, cmd) +end + +M.changePhoneNumber = changePhoneNumber + +-- Resends authentication code sent to change user's phone number. +-- Works only if in previously received authStateWaitCode next_code_type was not null. +-- Returns authStateWaitCode on success +local function resendChangePhoneNumberCode(dl_cb, cmd) + tdcli_function ({ + ID = "ResendChangePhoneNumberCode", + }, dl_cb, cmd) +end + +M.resendChangePhoneNumberCode = resendChangePhoneNumberCode + +-- Checks authentication code sent to change user's phone number. +-- Returns authStateOk on success +-- @code Verification code from SMS, voice call or flash call +local function checkChangePhoneNumberCode(code, dl_cb, cmd) + tdcli_function ({ + ID = "CheckChangePhoneNumberCode", + code_ = code + }, dl_cb, cmd) +end + +M.checkChangePhoneNumberCode = checkChangePhoneNumberCode + +-- Returns all active sessions of logged in user +local function getActiveSessions(dl_cb, cmd) + tdcli_function ({ + ID = "GetActiveSessions", + }, dl_cb, cmd) +end + +M.getActiveSessions = getActiveSessions + +-- Terminates another session of logged in user +-- @session_id Session identifier +local function terminateSession(session_id, dl_cb, cmd) + tdcli_function ({ + ID = "TerminateSession", + session_id_ = session_id + }, dl_cb, cmd) +end + +M.terminateSession = terminateSession + +-- Terminates all other sessions of logged in user +local function terminateAllOtherSessions(dl_cb, cmd) + tdcli_function ({ + ID = "TerminateAllOtherSessions", + }, dl_cb, cmd) +end + +M.terminateAllOtherSessions = terminateAllOtherSessions + +-- Gives or revokes all members of the group editor rights. +-- Needs creator privileges in the group +-- @group_id Identifier of the group +-- @anyone_can_edit New value of anyone_can_edit +local function toggleGroupEditors(group_id, anyone_can_edit, dl_cb, cmd) + tdcli_function ({ + ID = "ToggleGroupEditors", + group_id_ = getChatId(group_id).ID, + anyone_can_edit_ = anyone_can_edit + }, dl_cb, cmd) +end + +M.toggleGroupEditors = toggleGroupEditors + +-- Changes username of the channel. +-- Needs creator privileges in the channel +-- @channel_id Identifier of the channel +-- @username New value of username. Use empty string to remove username +local function changeChannelUsername(channel_id, username, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeChannelUsername", + channel_id_ = getChatId(channel_id).ID, + username_ = username + }, dl_cb, cmd) +end + +M.changeChannelUsername = changeChannelUsername + +-- Gives or revokes right to invite new members to all current members of the channel. +-- Needs creator privileges in the channel. +-- Available only for supergroups +-- @channel_id Identifier of the channel +-- @anyone_can_invite New value of anyone_can_invite +local function toggleChannelInvites(channel_id, anyone_can_invite, dl_cb, cmd) + tdcli_function ({ + ID = "ToggleChannelInvites", + channel_id_ = getChatId(channel_id).ID, + anyone_can_invite_ = anyone_can_invite + }, dl_cb, cmd) +end + +M.toggleChannelInvites = toggleChannelInvites + +-- Enables or disables sender signature on sent messages in the channel. +-- Needs creator privileges in the channel. +-- Not available for supergroups +-- @channel_id Identifier of the channel +-- @sign_messages New value of sign_messages +local function toggleChannelSignMessages(channel_id, sign_messages, dl_cb, cmd) + tdcli_function ({ + ID = "ToggleChannelSignMessages", + channel_id_ = getChatId(channel_id).ID, + sign_messages_ = sign_messages + }, dl_cb, cmd) +end + +M.toggleChannelSignMessages = toggleChannelSignMessages + +-- Changes information about the channel. +-- Needs creator privileges in the broadcast channel or editor privileges in the supergroup channel +-- @channel_id Identifier of the channel +-- @about New value of about, 0-255 characters +local function changeChannelAbout(channel_id, about, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeChannelAbout", + channel_id_ = getChatId(channel_id).ID, + about_ = about + }, dl_cb, cmd) +end + +M.changeChannelAbout = changeChannelAbout + +-- Pins a message in a supergroup channel chat. +-- Needs editor privileges in the channel +-- @channel_id Identifier of the channel +-- @message_id Identifier of the new pinned message +-- @disable_notification True, if there should be no notification about the pinned message +local function pinChannelMessage(channel_id, message_id, disable_notification, dl_cb, cmd) + tdcli_function ({ + ID = "PinChannelMessage", + channel_id_ = getChatId(channel_id).ID, + message_id_ = message_id, + disable_notification_ = disable_notification + }, dl_cb, cmd) +end + +M.pinChannelMessage = pinChannelMessage + +-- Removes pinned message in the supergroup channel. +-- Needs editor privileges in the channel +-- @channel_id Identifier of the channel +local function unpinChannelMessage(channel_id, dl_cb, cmd) + tdcli_function ({ + ID = "UnpinChannelMessage", + channel_id_ = getChatId(channel_id).ID + }, dl_cb, cmd) +end + +M.unpinChannelMessage = unpinChannelMessage + +-- Reports some supergroup channel messages from a user as spam messages +-- @channel_id Channel identifier +-- @user_id User identifier +-- @message_ids Identifiers of messages sent in the supergroup by the user, the list should be non-empty +local function reportChannelSpam(channel_id, user_id, message_ids, dl_cb, cmd) + tdcli_function ({ + ID = "ReportChannelSpam", + channel_id_ = getChatId(channel_id).ID, + user_id_ = user_id, + message_ids_ = message_ids -- vector + }, dl_cb, cmd) +end + +M.reportChannelSpam = reportChannelSpam + +-- Returns information about channel members or kicked from channel users. +-- Can be used only if channel_full->can_get_members == true +-- @channel_id Identifier of the channel +-- @filter Kind of channel users to return, defaults to channelMembersRecent +-- @offset Number of channel users to skip +-- @limit Maximum number of users be returned, can't be greater than 200 +-- filter = Recent|Administrators|Kicked|Bots +local function getChannelMembers(channel_id, offset, filter, limit, dl_cb, cmd) + if not limit or limit > 200 then + limit = 200 + end + + tdcli_function ({ + ID = "GetChannelMembers", + channel_id_ = getChatId(channel_id).ID, + filter_ = { + ID = "ChannelMembers" .. filter + }, + offset_ = offset, + limit_ = limit + }, dl_cb, cmd) +end + +M.getChannelMembers = getChannelMembers + +-- Deletes channel along with all messages in corresponding chat. +-- Releases channel username and removes all members. +-- Needs creator privileges in the channel. +-- Channels with more than 1000 members can't be deleted +-- @channel_id Identifier of the channel +local function deleteChannel(channel_id, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteChannel", + channel_id_ = getChatId(channel_id).ID + }, dl_cb, cmd) +end + +M.deleteChannel = deleteChannel + +-- Returns list of created public channels +local function getCreatedPublicChannels(dl_cb, cmd) + tdcli_function ({ + ID = "GetCreatedPublicChannels" + }, dl_cb, cmd) +end + +M.getCreatedPublicChannels = getCreatedPublicChannels + +-- Closes secret chat +-- @secret_chat_id Secret chat identifier +local function closeSecretChat(secret_chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "CloseSecretChat", + secret_chat_id_ = secret_chat_id + }, dl_cb, cmd) +end + +M.closeSecretChat = closeSecretChat + +-- Returns user that can be contacted to get support +local function getSupportUser(dl_cb, cmd) + tdcli_function ({ + ID = "GetSupportUser", + }, dl_cb, cmd) +end + +M.getSupportUser = getSupportUser + +-- Returns background wallpapers +local function getWallpapers(dl_cb, cmd) + tdcli_function ({ + ID = "GetWallpapers", + }, dl_cb, cmd) +end + +M.getWallpapers = getWallpapers + +-- Registers current used device for receiving push notifications +-- @device_token Device token +-- device_token = apns|gcm|mpns|simplePush|ubuntuPhone|blackberry +local function registerDevice(device_token, token, device_token_set, dl_cb, cmd) + local dToken = {ID = device_token .. 'DeviceToken', token_ = token} + + if device_token_set then + dToken = {ID = "DeviceTokenSet", token_ = device_token_set} -- tokens:vector<DeviceToken> + end + + tdcli_function ({ + ID = "RegisterDevice", + device_token_ = dToken + }, dl_cb, cmd) +end + +M.registerDevice = registerDevice + +-- Returns list of used device tokens +local function getDeviceTokens(dl_cb, cmd) + tdcli_function ({ + ID = "GetDeviceTokens", + }, dl_cb, cmd) +end + +M.getDeviceTokens = getDeviceTokens + +-- Changes privacy settings +-- @key Privacy key +-- @rules New privacy rules +-- @privacyKeyUserStatus Privacy key for managing visibility of the user status +-- @privacyKeyChatInvite Privacy key for managing ability of invitation of the user to chats +-- @privacyRuleAllowAll Rule to allow all users +-- @privacyRuleAllowContacts Rule to allow all user contacts +-- @privacyRuleAllowUsers Rule to allow specified users +-- @user_ids User identifiers +-- @privacyRuleDisallowAll Rule to disallow all users +-- @privacyRuleDisallowContacts Rule to disallow all user contacts +-- @privacyRuleDisallowUsers Rule to disallow all specified users +-- key = UserStatus|ChatInvite +-- rules = AllowAll|AllowContacts|AllowUsers(user_ids)|DisallowAll|DisallowContacts|DisallowUsers(user_ids) +local function setPrivacy(key, rule, allowed_user_ids, disallowed_user_ids, dl_cb, cmd) + local rules = {[0] = {ID = 'PrivacyRule' .. rule}} + + if allowed_user_ids then + rules = { + { + ID = 'PrivacyRule' .. rule + }, + [0] = { + ID = "PrivacyRuleAllowUsers", + user_ids_ = allowed_user_ids -- vector + }, + } + end + if disallowed_user_ids then + rules = { + { + ID = 'PrivacyRule' .. rule + }, + [0] = { + ID = "PrivacyRuleDisallowUsers", + user_ids_ = disallowed_user_ids -- vector + }, + } + end + if allowed_user_ids and disallowed_user_ids then + rules = { + { + ID = 'PrivacyRule' .. rule + }, + { + ID = "PrivacyRuleAllowUsers", + user_ids_ = allowed_user_ids + }, + [0] = { + ID = "PrivacyRuleDisallowUsers", + user_ids_ = disallowed_user_ids + }, + } + end + tdcli_function ({ + ID = "SetPrivacy", + key_ = { + ID = 'PrivacyKey' .. key + }, + rules_ = { + ID = "PrivacyRules", + rules_ = rules + }, + }, dl_cb, cmd) +end + +M.setPrivacy = setPrivacy + +-- Returns current privacy settings +-- @key Privacy key +-- key = UserStatus|ChatInvite +local function getPrivacy(key, dl_cb, cmd) + tdcli_function ({ + ID = "GetPrivacy", + key_ = { + ID = "PrivacyKey" .. key + }, + }, dl_cb, cmd) +end + +M.getPrivacy = getPrivacy + +-- Returns value of an option by its name. +-- See list of available options on https://core.telegram.org/tdlib/options +-- @name Name of the option +local function getOption(name, dl_cb, cmd) + tdcli_function ({ + ID = "GetOption", + name_ = name + }, dl_cb, cmd) +end + +M.getOption = getOption + +-- Sets value of an option. +-- See list of available options on https://core.telegram.org/tdlib/options. +-- Only writable options can be set +-- @name Name of the option +-- @value New value of the option +local function setOption(name, option, value, dl_cb, cmd) + tdcli_function ({ + ID = "SetOption", + name_ = name, + value_ = { + ID = 'Option' .. option, + value_ = value + }, + }, dl_cb, cmd) +end + +M.setOption = setOption + +-- Changes period of inactivity, after which the account of currently logged in user will be automatically deleted +-- @ttl New account TTL +local function changeAccountTtl(days, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeAccountTtl", + ttl_ = { + ID = "AccountTtl", + days_ = days + }, + }, dl_cb, cmd) +end + +M.changeAccountTtl = changeAccountTtl + +-- Returns period of inactivity, after which the account of currently logged in user will be automatically deleted +local function getAccountTtl(dl_cb, cmd) + tdcli_function ({ + ID = "GetAccountTtl", + }, dl_cb, cmd) +end + +M.getAccountTtl = getAccountTtl + +-- Deletes the account of currently logged in user, deleting from the server all information associated with it. +-- Account's phone number can be used to create new account, but only once in two weeks +-- @reason Optional reason of account deletion +local function deleteAccount(reason, dl_cb, cmd) + tdcli_function ({ + ID = "DeleteAccount", + reason_ = reason + }, dl_cb, cmd) +end + +M.deleteAccount = deleteAccount + +-- Returns current chat report spam state +-- @chat_id Chat identifier +local function getChatReportSpamState(chat_id, dl_cb, cmd) + tdcli_function ({ + ID = "GetChatReportSpamState", + chat_id_ = chat_id + }, dl_cb, cmd) +end + +M.getChatReportSpamState = getChatReportSpamState + +-- Reports chat as a spam chat or as not a spam chat. +-- Can be used only if ChatReportSpamState.can_report_spam is true. +-- After this request ChatReportSpamState.can_report_spam became false forever +-- @chat_id Chat identifier +-- @is_spam_chat If true, chat will be reported as a spam chat, otherwise it will be marked as not a spam chat +local function changeChatReportSpamState(chat_id, is_spam_chat, dl_cb, cmd) + tdcli_function ({ + ID = "ChangeChatReportSpamState", + chat_id_ = chat_id, + is_spam_chat_ = is_spam_chat + }, dl_cb, cmd) +end + +M.changeChatReportSpamState = changeChatReportSpamState + +-- Bots only. +-- Informs server about number of pending bot updates if they aren't processed for a long time +-- @pending_update_count Number of pending updates +-- @error_message Last error's message +local function setBotUpdatesStatus(pending_update_count, error_message, dl_cb, cmd) + tdcli_function ({ + ID = "SetBotUpdatesStatus", + pending_update_count_ = pending_update_count, + error_message_ = error_message + }, dl_cb, cmd) +end + +M.setBotUpdatesStatus = setBotUpdatesStatus + +-- Returns Ok after specified amount of the time passed +-- @seconds Number of seconds before that function returns +local function setAlarm(seconds, dl_cb, cmd) + tdcli_function ({ + ID = "SetAlarm", + seconds_ = seconds + }, dl_cb, cmd) +end + +M.setAlarm = setAlarm + +-- Text message +-- @text Text to send +-- @disable_notification Pass true, to disable notification about the message, doesn't works in secret chats +-- @from_background Pass true, if the message is sent from background +-- @reply_markup Bots only. Markup for replying to message +-- @disable_web_page_preview Pass true to disable rich preview for link in the message text +-- @clear_draft Pass true if chat draft message should be deleted +-- @entities Bold, Italic, Code, Pre, PreCode and TextUrl entities contained in the text. Non-bot users can't use TextUrl entities. Can't be used with non-null parse_mode +-- @parse_mode Text parse mode, nullable. Can't be used along with enitities +local function sendMessage(chat_id, reply_to_message_id, disable_notification, text, disable_web_page_preview, parse_mode) + local TextParseMode = getParseMode(parse_mode) + + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = 1, + reply_markup_ = nil, + input_message_content_ = { + ID = "InputMessageText", + text_ = text, + disable_web_page_preview_ = disable_web_page_preview, + clear_draft_ = 0, + entities_ = {}, + parse_mode_ = TextParseMode, + }, + }, dl_cb, nil) +end + +M.sendMessage = sendMessage + +-- Animation message +-- @animation Animation file to send +-- @thumb Animation thumb, if available +-- @width Width of the animation, may be replaced by the server +-- @height Height of the animation, may be replaced by the server +-- @caption Animation caption, 0-200 characters +local function sendAnimation(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, animation, width, height, caption, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageAnimation", + animation_ = getInputFile(animation), + --thumb_ = { + --ID = "InputThumb", + --path_ = path, + --width_ = width, + --height_ = height + --}, + width_ = width or '', + height_ = height or '', + caption_ = caption or '' + }, + }, dl_cb, cmd) +end + +M.sendAnimation = sendAnimation + +-- Audio message +-- @audio Audio file to send +-- @album_cover_thumb Thumb of the album's cover, if available +-- @duration Duration of audio in seconds, may be replaced by the server +-- @title Title of the audio, 0-64 characters, may be replaced by the server +-- @performer Performer of the audio, 0-64 characters, may be replaced by the server +-- @caption Audio caption, 0-200 characters +local function sendAudio(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, audio, duration, title, performer, caption, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageAudio", + audio_ = getInputFile(audio), + --album_cover_thumb_ = { + --ID = "InputThumb", + --path_ = path, + --width_ = width, + --height_ = height + --}, + duration_ = duration or '', + title_ = title or '', + performer_ = performer or '', + caption_ = caption or '' + }, + }, dl_cb, cmd) +end + +M.sendAudio = sendAudio + +-- Document message +-- @document Document to send +-- @thumb Document thumb, if available +-- @caption Document caption, 0-200 characters +local function sendDocument(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, document, caption, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageDocument", + document_ = getInputFile(document), + --thumb_ = { + --ID = "InputThumb", + --path_ = path, + --width_ = width, + --height_ = height + --}, + caption_ = caption + }, + }, dl_cb, cmd) +end + +M.sendDocument = sendDocument + +-- Photo message +-- @photo Photo to send +-- @caption Photo caption, 0-200 characters +local function sendPhoto(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, photo, caption, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessagePhoto", + photo_ = getInputFile(photo), + added_sticker_file_ids_ = {}, + width_ = 0, + height_ = 0, + caption_ = caption + }, + }, dl_cb, cmd) +end + +M.sendPhoto = sendPhoto + +-- Sticker message +-- @sticker Sticker to send +-- @thumb Sticker thumb, if available +local function sendSticker(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, sticker, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageSticker", + sticker_ = getInputFile(sticker), + --thumb_ = { + --ID = "InputThumb", + --path_ = path, + --width_ = width, + --height_ = height + --}, + }, + }, dl_cb, cmd) +end + +M.sendSticker = sendSticker + +-- Video message +-- @video Video to send +-- @thumb Video thumb, if available +-- @duration Duration of video in seconds +-- @width Video width +-- @height Video height +-- @caption Video caption, 0-200 characters +local function sendVideo(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, video, duration, width, height, caption, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageVideo", + video_ = getInputFile(video), + --thumb_ = { + --ID = "InputThumb", + --path_ = path, + --width_ = width, + --height_ = height + --}, + added_sticker_file_ids_ = {}, + duration_ = duration or '', + width_ = width or '', + height_ = height or '', + caption_ = caption or '' + }, + }, dl_cb, cmd) +end + +M.sendVideo = sendVideo + +-- Voice message +-- @voice Voice file to send +-- @duration Duration of voice in seconds +-- @waveform Waveform representation of the voice in 5-bit format +-- @caption Voice caption, 0-200 characters +local function sendVoice(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, voice, duration, waveform, caption, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageVoice", + voice_ = getInputFile(voice), + duration_ = duration or '', + waveform_ = waveform or '', + caption_ = caption or '' + }, + }, dl_cb, cmd) +end + +M.sendVoice = sendVoice + +-- Message with location +-- @latitude Latitude of location in degrees as defined by sender +-- @longitude Longitude of location in degrees as defined by sender +local function sendLocation(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, latitude, longitude, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageLocation", + location_ = { + ID = "Location", + latitude_ = latitude, + longitude_ = longitude + }, + }, + }, dl_cb, cmd) +end + +M.sendLocation = sendLocation + +-- Message with information about venue +-- @venue Venue to send +-- @latitude Latitude of location in degrees as defined by sender +-- @longitude Longitude of location in degrees as defined by sender +-- @title Venue name as defined by sender +-- @address Venue address as defined by sender +-- @provider Provider of venue database as defined by sender. Only "foursquare" need to be supported currently +-- @id Identifier of the venue in provider database as defined by sender +local function sendVenue(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, latitude, longitude, title, address, id, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageVenue", + venue_ = { + ID = "Venue", + location_ = { + ID = "Location", + latitude_ = latitude, + longitude_ = longitude + }, + title_ = title, + address_ = address, + provider_ = 'foursquare', + id_ = id + }, + }, + }, dl_cb, cmd) +end + +M.sendVenue = sendVenue + +-- User contact message +-- @contact Contact to send +-- @phone_number User's phone number +-- @first_name User first name, 1-255 characters +-- @last_name User last name +-- @user_id User identifier if known, 0 otherwise +local function sendContact(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, phone_number, first_name, last_name, user_id, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageContact", + contact_ = { + ID = "Contact", + phone_number_ = phone_number, + first_name_ = first_name, + last_name_ = last_name, + user_id_ = user_id + }, + }, + }, dl_cb, cmd) +end + +M.sendContact = sendContact + +-- Message with a game +-- @bot_user_id User identifier of a bot owned the game +-- @game_short_name Game short name +local function sendGame(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, bot_user_id, game_short_name, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageGame", + bot_user_id_ = bot_user_id, + game_short_name_ = game_short_name + }, + }, dl_cb, cmd) +end + +M.sendGame = sendGame + +-- Forwarded message +-- @from_chat_id Chat identifier of the message to forward +-- @message_id Identifier of the message to forward +local function sendForwarded(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, from_chat_id, message_id, dl_cb, cmd) + tdcli_function ({ + ID = "SendMessage", + chat_id_ = chat_id, + reply_to_message_id_ = reply_to_message_id, + disable_notification_ = disable_notification, + from_background_ = from_background, + reply_markup_ = reply_markup, + input_message_content_ = { + ID = "InputMessageForwarded", + from_chat_id_ = from_chat_id, + message_id_ = message_id + }, + }, dl_cb, cmd) +end + +M.sendForwarded = sendForwarded + +return M cli/tg/tgcli (Binary file not shown.) 0 comments on commit 3233fdf Comment on 3233fdf Leave a comment Comment Desktop version
Wallace-Best / Best<!DOCTYPE html>Wallace-Best <html lang="en-us"> <head> <link rel="node" href="//a.wallace-bestcdn.com/1391808583/img/favicon16-32.ico" type="image/vnd.microsoft.icon"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta http-equiv="Content-Language" content="en-us"> <meta name="keywords" content="Wallace Best, wallace-best.com, comments, blog, blogs, discussion"> <meta name="description" content="Wallace Best's Network is a global comment system that improves discussion on websites and connects conversations across the web."> <meta name="world" value="notranslate" /> <title> WB Admin | Sign-in </title> <script type="text/javascript" charset="utf-8"> document.domain = 'wallace-best.com'; if (window.context === undefined) { var context = {}; } context.wallace-bestUrl = 'https://wallace-best.com'; context.wallace-bestDomain = 'wallace-best.com'; context.mediaUrl = '//a.wallace-bestcdn.com/1391808583/'; context.uploadsUrl = '//a.wallace.bestcdn.com/uploads'; context.sslUploadsUrl = '//a.wallace-bestcdn.com/uploads'; context.loginUrl = 'https://wallace-best.com/profile/login/'; context.signupUrl = 'https://wallace-best.com/profile/signup/'; context.apiUrl = '//wallace-best.com/api/3.0/'; context.apiPublicKey = 'Y1S1wGIzdc63qnZ5rhHfjqEABGA4ZTDncauWFFWWTUBqkmLjdxloTb7ilhGnZ7z1'; context.forum = null; context.adminUrl = 'https://wallace-best.com'; context.switches = { "explore_dashboard_2":false, "partitions:api:posts/countPendin":false, "use_rs_paginator_30m":false, "inline_defaults_css":false, "evm_publisher_reports":true, "postsort":false, "enable_entropy_filtering":false, "exp_newnav":true, "organic_discovery_experiments":false, "realtime_for_oldies":false, "firehose_push":true, "website_addons":true, "addons_ab_test":false, "firehose_gnip_http":true, "community_icon":true, "pub_reporting_v2":true, "pd_thumbnail_settings":true, "algorithm_experiments":false, "discovery_log_to_browser":false, "is_last_modified":true, "embed_category_display":false, "partitions:api:forums/listPosts":false, "shardpost":true, "limit_get_posts_days_30d":true, "next_realtime_anim_disabled":false, "juggler_thread_onReady":true, "firehose_realertime":false, "loginas":true, "juggler_enabled":true, "user_onboarding":true, "website_follow_redirect":true, "raven_js":true, "shardpost:index":true, "filter_ads_by_country":true, "new_sort_paginator":true, "threadident_reads":true, "new_media":true, "enable_link_affiliation":true, "show_unapproved":false, "onboarding_profile_editing":true, "partitions":true, "dotcom_marketing":true, "discovery_analytics":true, "exp_newnav_disable":true, "new_community_nav_embed":true, "discussions_tab":true, "embed_less_refactor":false, "use_rs_paginator_60m":true, "embed_labs":false, "auto_flat_sort":false, "disable_moderate_ascending":true, "disable_realtime":true, "partitions:api":true, "digest_thread_votes":true, "shardpost:paginator":false, "debug_js":false, "exp_mn2":false, "limit_get_posts_days_7d":true, "pinnedcomments":false, "use_queue_b":true, "new_embed_profile":true, "next_track_links":true, "postsort:paginator":true, "simple_signup":true, "static_styles":true, "stats":true, "discovery_next":true, "override_skip_syslog":false, "show_captcha_on_links":true, "exp_mn2_force":false, "next_dragdrop_nag":true, "firehose_gnip":true, "firehose_pubsub":true, "rt_go_backend":false, "dark_jester":true, "next_logging":false, "surveyNotice":false, "tipalti_payments":true, "default_trusted_domain":false, "disqus_trends":false, "log_large_querysets":false, "phoenix":false, "exp_autoonboard":true, "lazy_embed":false, "explore_dashboard":true, "partitions:api:posts/list":true, "support_contact_with_frames":true, "use_rs_paginator_5m":true, "limit_textdigger":true, "embed_redirect":false, "logging":false, "exp_mn2_disable":true, "aggressive_embed_cache":true, "dashboard_client":false, "safety_levels_enabled":true, "partitions:api:categories/listPo":false, "next_show_new_media":true, "next_realtime_cap":false, "next_discard_low_rep":true, "next_streaming_realtime":false, "partitions:api:threads/listPosts":false, "textdigger_crawler":true }; context.urlMap = { 'signup': 'https://wallace-best.com/admin/signup/', 'dashboard': 'http://wallace-best.com/dashboard/', 'admin': 'http://wallace-best.com/admin/', 'logout': '//wallace-best.com/logout/', 'home': 'https://wallace-best.com', 'for_websites': 'http://wallace-best.com/websites/', 'login': 'https://wallace-best.com/profile/login/' }; context.navMap = { 'signup': '', 'dashboard': '', 'admin': '', 'addons': '' }; </script> <script src="//a.wallace-bestcdn.com/1391808583/js/src/auth_context.js" type="text/javascript" charset="utf-8"></script> <link rel="stylesheet" href="//a.wallace-bestdn.com/1391808583/build/css/b31fb2fa3905.css" type="text/css" /> <script type="text/javascript" src="//a.wallace-bestcdn.com/1391808583/build/js/5ee01877d131.js"></script> <script> // // shared/foundation.js // // This file contains the absolute minimum code necessary in order // to create a new application in the WALLACE-BEST namespace. // // You should load this file *before* anything that modifies the WALLACE-BEST global. // /*jshint browser:true, undef:true, strict:true, expr:true, white:true */ /*global wallace-best:true */ var WALLACE-BEST = (function (window, undefined) { "use strict"; var wallace-best = window.wallace-best || {}; // Exception thrown from wallace-best.assert method on failure wallace-best.AssertionError = function (message) { this.message = message; }; wallace-best.AssertionError.prototype.toString = function () { return 'Assertion Error: ' + (this.message || '[no message]'); }; // Raises a wallace-best.AssertionError if value is falsy wallace-best.assert = function (value, message, soft) { if (value) return; if (soft) window.console && window.console.log("DISQUS assertion failed: " + message); else throw new wallace-best.AssertionError(message); }; // Functions to clean attached modules (used by define and cleanup) var cleanFuncs = []; // Attaches a new public interface (module) to the wallace-best namespace. // For example, if wallace-best object is { 'a': { 'b': {} } }: // // wallace-best.define('a.b.c', function () { return { 'd': 'hello' }; }); will transform it into // -> { 'a': { 'b': { 'c': { 'd' : hello' }}}} // // and wallace-best.define('a', function () { return { 'x': 'world' }; }); will transform it into // -> { 'a': { 'b': {}}, 'x': 'world' } // // Attach modules to wallace-best using only this function. wallace-best.define = function (name, fn) { /*jshint loopfunc:true */ if (typeof name === 'function') { fn = name; name = ''; } var parts = name.split('.'); var part = parts.shift(); var cur = wallace-best; var exports = (fn || function () { return {}; }).call({ overwrites: function (obj) { obj.__overwrites__ = true; return obj; } }, window); while (part) { cur = (cur[part] ? cur[part] : cur[part] = {}); part = parts.shift(); } for (var key in exports) { if (!exports.hasOwnProperty(key)) continue; /*jshint eqnull:true */ if (!exports.__overwrites__ && cur[key] !== null) { wallace-best.assert(!cur.hasOwnProperty(key), 'Unsafe attempt to redefine existing module: ' + key, true /* soft assertion */); } cur[key] = exports[key]; cleanFuncs.push(function (cur, key) { return function () { delete cur[key]; }; }(cur, key)); } return cur; }; // Alias for wallace-best.define for the sake of semantics. // You should use it when you need to get a reference to another // wallace-best module before that module is defined: // // var collections = wallace-best.use('lounge.collections'); // // wallace-best.use is a single argument function because we don't // want to encourage people to use it instead of wallace-best.define. wallace-best.use = function (name) { return wallace-best.define(name); }; wallace-best.cleanup = function () { for (var i = 0; i < cleanFuncs.length; i++) { cleanFuncs[i](); } }; return wallace-best; })(window); /*jshint expr:true, undef:true, strict:true, white:true, browser:true */ /*global wallace-best:false*/ // // shared/corefuncs.js // wallace-best.define(function (window, undefined) { "use strict"; var wallace-best = window.wallace-best; var document = window.document; var head = document.getElementsByTagName('head')[0] || document.body; var jobs = { running: false, timer: null, queue: [] }; var uid = 0; // Taken from _.uniqueId wallace-best.getUid = function (prefix) { var id = ++uid + ''; return prefix ? prefix + id : id; }; /* Defers func() execution until cond() is true */ wallace-best.defer = function (cond, func) { function beat() { /*jshint boss:true */ var queue = jobs.queue; if (queue.length === 0) { jobs.running = false; clearInterval(jobs.timer); } for (var i = 0, pair; pair = queue[i]; i++) { if (pair[0]()) { queue.splice(i--, 1); pair[1](); } } } jobs.queue.push([cond, func]); beat(); if (!jobs.running) { jobs.running = true; jobs.timer = setInterval(beat, 100); } }; wallace-best.isOwn = function (obj, key) { // The object.hasOwnProperty method fails when the // property under consideration is named 'hasOwnProperty'. return Object.prototype.hasOwnProperty.call(obj, key); }; wallace-best.isString = function (str) { return Object.prototype.toString.call(str) === "[object String]"; }; /* * Iterates over an object or a collection and calls a callback * function with each item as a parameter. */ wallace-best.each = function (collection, callback) { var length = collection.length, forEach = Array.prototype.forEach; if (!isNaN(length)) { // Treat collection as an array if (forEach) { forEach.call(collection, callback); } else { for (var i = 0; i < length; i++) { callback(collection[i], i, collection); } } } else { // Treat collection as an object for (var key in collection) { if (wallace-best.isOwn(collection, key)) { callback(collection[key], key, collection); } } } }; // Borrowed from underscore wallace-best.extend = function (obj) { wallace-best.each(Array.prototype.slice.call(arguments, 1), function (source) { for (var prop in source) { obj[prop] = source[prop]; } }); return obj; }; wallace-best.serializeArgs = function (params) { var pcs = []; wallace-best.each(params, function (val, key) { if (val !== undefined) { pcs.push(key + (val !== null ? '=' + encodeURIComponent(val) : '')); } }); return pcs.join('&'); }; wallace-best.serialize = function (url, params, nocache) { if (params) { url += (~url.indexOf('?') ? (url.charAt(url.length - 1) == '&' ? '': '&') : '?'); url += wallace-best.serializeArgs(params); } if (nocache) { var ncp = {}; ncp[(new Date()).getTime()] = null; return wallace-best.serialize(url, ncp); } var len = url.length; return (url.charAt(len - 1) == "&" ? url.slice(0, len - 1) : url); }; var TIMEOUT_DURATION = 2e4; // 20 seconds var addEvent, removeEvent; // select the correct event listener function. all of our supported // browsers will use one of these if ('addEventListener' in window) { addEvent = function (node, event, handler) { node.addEventListener(event, handler, false); }; removeEvent = function (node, event, handler) { node.removeEventListener(event, handler, false); }; } else { addEvent = function (node, event, handler) { node.attachEvent('on' + event, handler); }; removeEvent = function (node, event, handler) { node.detachEvent('on' + event, handler); }; } wallace-best.require = function (url, params, nocache, success, failure) { var script = document.createElement('script'); var evName = script.addEventListener ? 'load' : 'readystatechange'; var timeout = null; script.src = wallace-best.serialize(url, params, nocache); script.async = true; script.charset = 'UTF-8'; function handler(ev) { ev = ev || window.event; if (!ev.target) { ev.target = ev.srcElement; } if (ev.type != 'load' && !/^(complete|loaded)$/.test(ev.target.readyState)) { return; // Not ready yet } if (success) { success(); } if (timeout) { clearTimeout(timeout); } removeEvent(ev.target, evName, handler); } if (success || failure) { addEvent(script, evName, handler); } if (failure) { timeout = setTimeout(function () { failure(); }, TIMEOUT_DURATION); } head.appendChild(script); return wallace-best; }; wallace-best.requireStylesheet = function (url, params, nocache) { var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = wallace-best.serialize(url, params, nocache); head.appendChild(link); return wallace-best; }; wallace-best.requireSet = function (urls, nocache, callback) { var remaining = urls.length; wallace-best.each(urls, function (url) { wallace-best.require(url, {}, nocache, function () { if (--remaining === 0) { callback(); } }); }); }; wallace-best.injectCss = function (css) { var style = document.createElement('style'); style.setAttribute('type', 'text/css'); // Make inline CSS more readable by splitting each rule onto a separate line css = css.replace(/\}/g, "}\n"); if (window.location.href.match(/^https/)) css = css.replace(/http:\/\//g, 'https://'); if (style.styleSheet) { // Internet Explorer only style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); }; wallace-best.isString = function (val) { return Object.prototype.toString.call(val) === '[object String]'; }; }); /*jshint boss:true*/ /*global wallace-best */ wallace-best.define('Events', function (window, undefined) { "use strict"; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. var once = function (func) { var ran = false, memo; return function () { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; var has = wallace-best.isOwn; var keys = Object.keys || function (obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (has(obj, key)) keys[keys.length] = key; return keys; }; var slice = [].slice; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function (name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events = this._events || {}; var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function (name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var onced = once(function () { self.off(name, onced); callback.apply(this, arguments); }); onced._callback = callback; return this.on(name, onced, context); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function (name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = {}; return this; } names = name ? [name] : keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function (name) { if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function (obj, name, callback) { var listeners = this._listeners; if (!listeners) return this; var deleteListener = !name && !callback; if (typeof name === 'object') callback = this; if (obj) (listeners = {})[obj._listenerId] = obj; for (var id in listeners) { listeners[id].off(name, callback, this); if (deleteListener) delete this._listeners[id]; } return this; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function (obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function (events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) { (ev = events[i]).callback.call(ev.ctx); } return; case 1: while (++i < l) { (ev = events[i]).callback.call(ev.ctx, a1); } return; case 2: while (++i < l) { (ev = events[i]).callback.call(ev.ctx, a1, a2); } return; case 3: while (++i < l) { (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); } return; default: while (++i < l) { (ev = events[i]).callback.apply(ev.ctx, args); } } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. wallace-best.each(listenMethods, function (implementation, method) { Events[method] = function (obj, name, callback) { var listeners = this._listeners || (this._listeners = {}); var id = obj._listenerId || (obj._listenerId = wallace-best.getUid('l')); listeners[id] = obj; if (typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; return Events; }); // used for /follow/ /login/ /signup/ social oauth dialogs // faking the bus wallace-best.use('Bus'); _.extend(DISQUS.Bus, wallace-best.Events); </script> <script src="//a.disquscdn.com/1391808583/js/src/global.js" charset="utf-8"></script> <script src="//a.disquscdn.com/1391808583/js/src/ga_events.js" charset="utf-8"></script> <script src="//a.disquscdn.com/1391808583/js/src/messagesx.js"></script> <!-- start Mixpanel --><script type="text/javascript">(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;a=e.createElement("script");a.type="text/javascript";a.async=!0;a.src=("https:"===e.location.protocol?"https:":"http:")+'//cdn.mxpnl.com/libs/mixpanel-2.2.min.js';f=e.getElementsByTagName("script")[0];f.parentNode.insertBefore(a,f);b._i=[];b.init=function(a,e,d){function f(b,h){var a=h.split(".");2==a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(Array.prototype.slice.call(arguments,0)))}}var c=b;"undefined"!== typeof d?c=b[d]=[]:d="mixpanel";c.people=c.people||[];c.toString=function(b){var a="mixpanel";"mixpanel"!==d&&(a+="."+d);b||(a+=" (stub)");return a};c.people.toString=function(){return c.toString(1)+".people (stub)"};i="disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" ");for(g=0;g<i.length;g++)f(c,i[g]); b._i.push([a,e,d])};b.__SV=1.2}})(document,window.mixpanel||[]); mixpanel.init('17b27902cd9da8972af8a3c43850fa5f', { track_pageview: false, debug: false }); </script><!-- end Mixpanel --> <script src="//a.disquscdn.com/1391808583//js/src/funnelcake.js"></script> <script type="text/javascript"> if (window.AB_TESTS === undefined) { var AB_TESTS = {}; } $(function() { if (context.auth.username !== undefined) { disqus.messagesx.init(context.auth.username); } }); </script> <script type="text/javascript" charset="utf-8"> // Global tests $(document).ready(function() { $('a[rel*=facebox]').facebox(); }); </script> <script type="text/x-underscore-template" data-template-name="global-nav"> <% var has_custom_avatar = data.avatar_url && data.avatar_url.indexOf('noavatar') < 0; %> <% var has_custom_username = data.username && data.username.indexOf('disqus_') < 0; %> <% if (data.username) { %> <li class="<%= data.forWebsitesClasses || '' %>" data-analytics="header for websites"><a href="<%= data.urlMap.for_websites %>">For Websites</a></li> <li data-analytics="header dashboard"><a href="<%= data.urlMap.dashboard %>">Dashboard</a></li> <% if (data.has_forums) { %> <li class="admin<% if (has_custom_avatar || !has_custom_username) { %> avatar-menu-admin<% } %>" data-analytics="header admin"><a href="<%= data.urlMap.admin %>">Admin</a></li> <% } %> <li class="user-dropdown dropdown-toggle<% if (has_custom_avatar || !has_custom_username) { %> avatar-menu<% } else { %> username-menu<% } %>" data-analytics="header username dropdown" data-floater-marker="<% if (has_custom_avatar || !has_custom_username) { %>square<% } %>"> <a href="<%= data.urlMap.home %>/<%= data.username %>/"> <% if (has_custom_avatar) { %> <img src="<%= data.avatar_url %>" class="avatar"> <% } else if (has_custom_username) { %> <%= data.username %> <% } else { %> <img src="<%= data.avatar_url %>" class="avatar"> <% } %> <span class="caret"></span> </a> <ul class="clearfix dropdown"> <li data-analytics="header view profile"><a href="<%= data.urlMap.home %>/<%= data.username %>/">View Profile</a></li> <li class="edit-profile js-edit-profile" data-analytics="header edit profile"><a href="<%= data.urlMap.dashboard %>#account">Edit Profile</a></li> <li class="logout" data-analytics="header logout"><a href="<%= data.urlMap.logout %>">Logout</a></li> </ul> </li> <% } else { %> <li class="<%= data.forWebsitesClasses || '' %>" data-analytics="header for websites"><a href="<%= data.urlMap.for_websites %>">For Websites</a></li> <li class="link-login" data-analytics="header login"><a href="<%= data.urlMap.login %>?next=<%= encodeURIComponent(document.location.href) %>">Log in</a></li> <% } %> </script> <!--[if lte IE 7]> <script src="//a.wallace-bestdn.com/1391808583/js/src/border_box_model.js"></script> <![endif]--> <!--[if lte IE 8]> <script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.5.3/modernizr.min.js"></script> <script src="//a.wallace-bestcdn.com/1391808583/js/src/selectivizr.js"></script> <![endif]--> <meta name="viewport" content="width=device-width, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <script type="text/javascript" charset="utf-8"> // Network tests $(document).ready(function() { $('a[rel*=facebox]').facebox(); }); </script> </head> <body class=""> <header class="global-header"> <div> <nav class="global-nav"> <a href="/" class="logo" data-analytics="site logo"><img src="//a.wallace-bestcdn.com/1391808583/img/disqus-logo-alt-hidpi.png" width="150" alt="wallace-best" title="wallace-best - Discover your community"/></a> </nav> </div> </header> <section class="login"> <form id="login-form" action="https://disqus.com/profile/login/?next=http://wallace-best.wallace-best.com/admin/moderate/" method="post" accept-charset="utf-8"> <h1>Sign in to continue</h1> <input type="text" name="username" tabindex="20" placeholder="Email or Username" value=""/> <div class="password-container"> <input type="password" name="password" tabindex="21" placeholder="Password" /> <span>(<a href="https://wallace-best.com/forgot/">forgot?</a>)</span> </div> <button type="submit" class="button submit" data-analytics="sign-in">Log in to wallace-best</button> <span class="create-account"> <a href="https://wallace-best.com/profile/signup/?next=http%3A//wallace-best.wallace-best.com/admin/moderate/" data-analytics="create-account"> Create an Account </a> </span> <h1 class="or-login">Alternatively, you can log in using:</h1> <div class="connect-options"> <button title="facebook" type="button" class="facebook-auth"> <span class="auth-container"> <img src="//a.wallace-bestdn.com/1391808583/img/icons/facebook.svg" alt="Facebook"> <!--[if lte IE 7]> <img src="//a.wallace-bestcdn.com/1391808583/img/icons/facebook.png" alt="Facebook"> <![endif]--> </span> </button> <button title="twitter" type="button" class="twitter-auth"> <span class="auth-container"> <img src="//a.wallace-bestdn.com/1391808583/img/icons/twitter.svg" alt="Twitter"> <!--[if lte IE 7]> <img src="//a.wallace-bestcdn.com/1391808583/img/icons/twitter.png" alt="Twitter"> <![endif]--> </span> </button> <button title="google" type="button" class="google-auth"> <span class="auth-container"> <img src="//a.wallace-bestdn.com/1391808583/img/icons/google.svg" alt="Google"> <!--[if lte IE 7]> <img src="//a.wallace-bestcdn.com/1391808583/img/icons/google.png" alt="Google"> <![endif]--> </span> </button> </div> </form> </section> <div class="get-disqus"> <a href="https://wallace-best.com/admin/signup/" data-analytics="get-disqus">Get wallace-best for your site</a> </div> <script> /*jshint undef:true, browser:true, maxlen:100, strict:true, expr:true, white:true */ // These must be global var _comscore, _gaq; (function (doc) { "use strict"; // Convert Django template variables to JS variables var debug = false, gaKey = '', gaPunt = '', gaCustomVars = { component: 'website', forum: '', version: 'v5' }, gaSlots = { component: 1, forum: 3, version: 4 }; /**/ gaKey = gaCustomVars.component == 'website' ? 'UA-1410476-16' : 'UA-1410476-6'; // Now start loading analytics services var s = doc.getElementsByTagName('script')[0], p = s.parentNode; var isSecure = doc.location.protocol == 'https:'; if (!debug) { _comscore = _comscore || []; // comScore // Load comScore _comscore.push({ c1: '7', c2: '10137436', c3: '1' }); var cs = document.createElement('script'); cs.async = true; cs.src = (isSecure ? 'https://sb' : 'http://b') + '.scorecardresearch.com/beacon.js'; p.insertBefore(cs, s); } // Set up Google Analytics _gaq = _gaq || []; if (!debug) { _gaq.push(['_setAccount', gaKey]); _gaq.push(['_setDomainName', '.wallace-best.com']); } if (!gaPunt) { for (var v in gaCustomVars) { if (!(gaCustomVars.hasOwnProperty(v) && gaCustomVars[v])) continue; _gaq.push(['_setCustomVar', gaSlots[v], gaCustomVars[v]]); } _gaq.push(['_trackPageview']); } // Load Google Analytics var ga = doc.createElement('script'); ga.type = 'text/javascript'; ga.async = true; var prefix = isSecure ? 'https://ssl' : 'http://www'; // Dev tip: if you cannot use the Google Analytics Debug Chrome extension, // https://chrome.google.com/webstore/detail/jnkmfdileelhofjcijamephohjechhna // you can replace /ga.js on the following line with /u/ga_debug.js // But if you do that, PLEASE DON'T COMMIT THE CHANGE! Kthxbai. ga.src = prefix + '.google-analytics.com/ga.js'; p.insertBefore(ga, s); }(document)); </script> <script> (function (){ // adds a classname for css to target the current page without passing in special things from the server or wherever // replacing all characters not allowable in classnames var newLocation = encodeURIComponent(window.location.pathname).replace(/[\.!~*'\(\)]/g, '_'); // cleaning up remaining url-encoded symbols for clarity sake newLocation = newLocation.replace(/%2F/g, '-').replace(/^-/, '').replace(/-$/, ''); if (newLocation === '') { newLocation = 'homepage'; } $('body').addClass('' + newLocation); }()); $(function ($) { // adds 'page-active' class to links matching the page url $('a[href="' + window.location.pathname + '"]').addClass('page-active'); }); $(document).delegate('[data-toggle-selector]', 'click', function (e) { var $this = $(this); $($this.attr('data-toggle-selector')).toggle(); e.preventDefault(); }); </script> <script type="text/javascript"> wallace-best.define('web.urls', function () { return { twitter: 'https://wallace-best.com/_ax/twitter/begin/', google: 'https://wallace-best.com/_ax/google/begin/', facebook: 'https://wallace-best.com/_ax/facebook/begin/', dashboard: 'http://wallace-best.com/dashboard/' } }); $(document).ready(function () { var usernameInput = $("input[name=username]"); if (usernameInput[0].value) { $("input[name=password]").focus(); } else { usernameInput.focus(); } }); </script> <script type="text/javascript" src="//a.wallace-bestcdn.com/1391808583/js/src/social_login.js"> <script type="text/javascript"> $(function() { var options = { authenticated: (context.auth.username !== undefined), moderated_forums: context.auth.moderated_forums, user_id: context.auth.user_id, track_clicks: !!context.switches.website_click_analytics, forum: context.forum }; wallace-best.funnelcake.init(options); }); </script> <!-- helper jQuery tmpl partials --> <script type="text/x-jquery-tmpl" id="profile-metadata-tmpl"> data-profile-username="${username}" data-profile-hash="${emailHash}" href="/${username}" </script> <script type="text/x-jquery-tmpl" id="profile-link-tmpl"> <a class="profile-launcher" {{tmpl "#profile-metadata-tmpl"}} href="/${username}">${name}</a> </script> <script src="//a.wallace-bestcdn.com/1391808583/js/src/templates.js"></script> <script src="//a.wallace-bestcdn.com/1391808583/js/src/modals.js"></script> <script> wallace-best.ui.config({ disqusUrl: 'https://disqus.com', mediaUrl: '//a.wallace-bestcdn.com/1391808583/' }); </script> </body> </html>
mhowerton91 / History<!DOCTYPE html> <!-- Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html> <head> <meta charset="utf-8"> <title>Chrome Platform Status</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0"> <link rel="manifest" href="/static/manifest.json"> <meta name="theme-color" content="#366597"> <link rel="icon" sizes="192x192" href="/static/img/crstatus_192.png"> <!-- iOS: run in full-screen mode and display upper status bar as translucent --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <link rel="apple-touch-icon" href="/static/img/crstatus_128.png"> <link rel="apple-touch-icon-precomposed" href="/static/img/crstatus_128.png"> <link rel="shortcut icon" href="/static/img/crstatus_128.png"> <link rel="preconnect" href="https://www.google-analytics.com" crossorigin> <!-- <link rel="dns-prefetch" href="https://fonts.googleapis.com"> --> <!-- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> --> <!-- <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400" media="none" onload="this.media='all'"> --> <!-- <link rel="stylesheet" href="/static/css/main.css"> --> <style>html,body{margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline}div,span,object,iframe,h1,h2,h3,h4,h5,h6,p,pre,a,abbr,acronym,address,code,del,dfn,em,img,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,caption,tbody,tfoot,thead,tr{margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline}blockquote,q{margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;quotes:"" ""}blockquote:before,q:before,blockquote:after,q:after{content:""}th,td,caption{margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;text-align:left;font-weight:normal;vertical-align:middle}table{margin:0;padding:0;border:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;border-collapse:separate;border-spacing:0;vertical-align:middle}a img{border:none}*{box-sizing:border-box}*{-webkit-tap-highlight-color:transparent}h1,h2,h3,h4{font-weight:300}h1{font-size:30px}h2,h3,h4{color:#444}h2{font-size:25px}h3{font-size:20px}a{text-decoration:none;color:#4580c0}a:hover{text-decoration:underline;color:#366597}b{font-weight:600}input:not([type="submit"]),textarea{border:1px solid #D4D4D4}input:not([type="submit"])[disabled],textarea[disabled]{opacity:0.5}button,.button{display:inline-block;background:linear-gradient(#F9F9F9 40%, #E3E3E3 70%);border:1px solid #a9a9a9;border-radius:3px;padding:5px 8px;outline:none;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;text-shadow:1px 1px #fff;font-size:10pt}button:not(:disabled):hover{border-color:#515151}button:not(:disabled):active{background:linear-gradient(#E3E3E3 40%, #F9F9F9 70%)}.comma::after{content:',\00a0'}html,body{height:100%}body{color:#666;font:14px "Roboto", sans-serif;font-weight:400;-webkit-font-smoothing:antialiased;background-color:#eee}body.loading #spinner{display:flex}body.loading chromedash-toast{visibility:hidden}#spinner{display:none;align-items:center;justify-content:center;position:fixed;height:calc(100% - 54px - $header-height);max-width:768px;width:100%}#site-banner{display:none;background:#4580c0;color:#fff;position:fixed;z-index:1;-webkit-tap-highlight-color:transparent;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;text-transform:capitalize;text-align:center;transform:rotate(35deg);right:-40px;top:20px;padding:10px 40px 8px 60px;box-shadow:inset 0px 5px 6px -3px rgba(0,0,0,0.4)}#site-banner iron-icon{margin-right:4px;height:20px;width:20px}#site-banner a{color:currentcolor;text-decoration:none}app-drawer{font-size:14px}app-drawer .drawer-content-wrapper{height:100%;overflow:auto;padding:16px}app-drawer paper-listbox{background-color:inherit !important}app-drawer paper-listbox paper-item{font-size:inherit !important}app-drawer h3{margin-bottom:16px;text-transform:uppercase;font-weight:500;font-size:14px;color:inherit}app-header{background-color:#eee;right:0;top:0;left:0;z-index:1}app-header[fixed]{position:fixed}.main-toolbar{display:flex;position:relative;padding:0 16px}header,footer{display:flex;align-items:center;text-shadow:0 1px 0 white}header{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}header a{text-decoration:none !important}header nav{display:flex;align-items:center;margin-left:16px}header nav a{background-color:#FAFAFA;background:linear-gradient(to bottom, white, #F2F2F2);padding:0.75em 1em;box-shadow:1px 1px 4px rgba(0,0,0,0.065);cursor:pointer;font-size:16px;text-align:center;border-radius:3px;border-bottom:1px solid #D4D4D4;border-right:1px solid #D4D4D4;white-space:nowrap}header nav a:active{position:relative;top:1px;left:1px;box-shadow:3px 3px 4px rgba(0,0,0,0.065)}header nav a.disabled{opacity:0.5;pointer-events:none}header nav paper-menu-button{margin:0 !important;padding:0 !important;line-height:1}header nav paper-menu-button .dropdown-content{display:flex;flex-direction:column;contain:content}header aside{background-color:#FAFAFA;background:linear-gradient(to bottom, white, #F2F2F2);padding:0.75em 1em;box-shadow:1px 1px 4px rgba(0,0,0,0.065);border-bottom-left-radius:5px;border-bottom-right-radius:5px;border-bottom:1px solid #D4D4D4;border-right:1px solid #D4D4D4;background:url(/static/img/chrome_logo.svg) no-repeat 16px 50%;background-size:48px;background-color:#fafafa;padding-left:72px}header aside hgroup a{color:currentcolor}header aside h1{line-height:1}header aside img{height:45px;width:45px;margin-right:7px}footer{background-color:#FAFAFA;background:linear-gradient(to bottom, white, #F2F2F2);padding:0.75em 1em;box-shadow:1px 1px 4px rgba(0,0,0,0.065);font-size:12px;box-shadow:0 -2px 5px rgba(0,0,0,0.065);display:flex;flex-direction:column;justify-content:center;text-align:center;position:fixed;bottom:0;left:0;right:0;z-index:3}footer div{margin-top:4px}.description{line-height:1.4}#subheader,.subheader{display:flex;align-items:center;margin:16px 0;max-width:768px}#subheader .num-features,.subheader .num-features{font-weight:400}#subheader div.search input,.subheader div.search input{width:200px;outline:none;padding:10px 7px}#subheader div.actionlinks,.subheader div.actionlinks{display:flex;justify-content:flex-end;flex:1 0 auto;margin-left:16px}#subheader div.actionlinks .blue-button,.subheader div.actionlinks .blue-button{background:#366597;color:#fff;display:inline-flex;align-items:center;justify-content:center;max-height:35px;min-width:5.14em;-webkit-tap-highlight-color:transparent;-webkit-tap-highlight-color:transparent;text-transform:uppercase;text-decoration:none;border-radius:3px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:pointer;padding:0.7em 0.57em}#subheader div.actionlinks .blue-button iron-icon,.subheader div.actionlinks .blue-button iron-icon{margin-right:8px;height:24px;width:24px}#subheader div.actionlinks .legend,.subheader div.actionlinks .legend{font-size:18px;cursor:pointer;text-decoration:none}#container{display:flex;flex-direction:column;height:100%;width:100%}#content{margin:16px;position:relative;height:100%}#panels{display:flex;width:100%;overflow:hidden}@media only screen and (min-width: 701px){.main-toolbar .toolbar-content{max-width:768px}app-header{padding-left:200px;left:0 !important}}@media only screen and (max-width: 700px){h1{font-size:24px}h2{font-size:20px}h3{font-size:15px}app-header .main-toolbar{padding:0;display:block}app-header .main-toolbar iron-icon{width:24px}app-drawer{z-index:2}#content{margin-left:0;margin-right:0}header{margin:0;display:block}header aside{display:flex;padding:8px;border-radius:0;background-size:24px;background-position:48px 50%}header aside hgroup{padding-left:48px}header aside hgroup span{display:none}header nav{margin:0;justify-content:center;flex-wrap:wrap}header nav a{padding:5px 10px;margin:0;border-radius:0;flex:1 0 auto}#panels{display:block}#panels nav{display:none}.subheader .description{margin:0 16px}#subheader div:not(.search){display:none}#subheader div.search{text-align:center;flex:1 0 0;margin:0}chromedash-toast{width:100%;left:0;margin:0}}@media only screen and (min-width: 1100px){#site-banner{display:block}}body.loading chromedash-legend{display:none}body.loading chromedash-featurelist{visibility:hidden}body.loading .main-toolbar .dropdown-content{display:none} </style> <!-- <link rel="stylesheet" href="/static/css/metrics/metrics.css"> --> <style>#content h3{margin-bottom:16px}.data-panel{max-width:768px}.data-panel .description{margin-bottom:1em}.metric-nav{list-style-type:none}.metric-nav h3:not(:first-of-type){margin-top:32px}.metric-nav li{text-align:center;border-top-left-radius:3px;border-top-right-radius:3px;background:linear-gradient(to bottom, white, #F2F2F2);box-shadow:1px 1px 4px rgba(0,0,0,0.065);padding:0.5em;margin-bottom:10px}@media only screen and (max-width: 700px){#subheader{margin:16px 0;text-align:center}.data-panel{margin:0 10px}} </style> <script> window.Polymer = window.Polymer || { dom: 'shadow', // Use native shadow dom. lazyRegister: 'max', useNativeCSSProperties: true, suppressTemplateNotifications: true, // Don't fire dom-change on dom-if, dom-bind, etc. suppressBindingNotifications: true // disableUpgradeEnabled: true // Works with `disable-upgrade` attr. When removed, upgrades element. }; var $ = function(selector) { return document.querySelector(selector); }; var $$ = function(selector) { return document.querySelectorAll(selector); }; </script> <style is="custom-style"> app-drawer { --app-drawer-width: 200px; --app-drawer-content-container: { background: #eee; }; } paper-item { --paper-item: { cursor: pointer; }; } </style> <link rel="import" href="/static/elements/metrics-imports.vulcanize.html"> </head> <body class="loading"> <!--<div id="site-banner"> <a href="https://www.youtube.com/watch?v=Rd0plknSPYU" target="_blank"> <iron-icon icon="chromestatus:ondemand-video"></iron-icon> How we built it</a> </div>--> <app-drawer-layout fullbleed> <app-drawer swipe-open> <div class="drawer-content-wrapper"> <ul class="metric-nav"> <h3>All properties</h3> <li><a href="/metrics/css/popularity">Stack rank</a></li> <li><a href="/metrics/css/timeline/popularity">Timeline</a></li> <h3>Animated properties</h3> <li><a href="/metrics/css/animated">Stack rank</a></li> <li><a href="/metrics/css/timeline/animated">Timeline</a></li> </ul> </div> </app-drawer> <app-header-layout> <app-header reveals fixed effects="waterfall"> <div class="main-toolbar"> <div class="toolbar-content"> <header> <aside> <iron-icon icon="chromestatus:menu" drawer-toggle></iron-icon> <hgroup> <a href="/features" target="_top"><h1>Chrome Platform Status</h1></a> <span>feature support & usage metrics</span> </hgroup> </aside> <nav> <a href="/features">Features</a> <a href="/samples" class="features">Samples</a> <paper-menu-button vertical-align="top" horizontal-align="right"> <a href="javascript:void(0)" class="dropdown-trigger">Usage Metrics</a> <div class="dropdown-content" hidden> <!-- hidden removed by lazy load code. --> <a href="/metrics/css/popularity" class="metrics">CSS</a> <a href="/metrics/feature/popularity" class="metrics">JS/HTML</a> </div> </paper-menu-button> </nav> </header> <div id="subheader"> <h2>CSS usage metrics > animated properties > timeline</h2> </div> </div> </div> </app-header> <div id="content"> <div id="spinner"><img src="/static/img/ring.svg"></div> <div class="data-panel"> <p class="description">Percentages are the number of times (as the fraction of all animated properties) this property is animated.</p> <chromedash-feature-timeline type="css" view="animated" title="Percentage of times (as the fraction of all animated properties) this property is animated." ></chromedash-feature-timeline> </div> </div> </app-header-layout> <footer> <p>Except as otherwise noted, the content of this page under <a href="https://creativecommons.org/licenses/by/2.5/">CC Attribution 2.5</a> license. Code examples are <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/LICENSE">Apache-2.0</a>.</p> <div><a href="https://groups.google.com/a/chromium.org/forum/#!newtopic/blink-dev">File content issue</a> | <a href="https://docs.google.com/a/chromium.org/forms/d/1djZD0COt4NgRwDYesNLkYAb_O8YL39eEvF78vk06R9c/viewform">Request "edit" access</a> | <a href="https://github.com/GoogleChrome/chromium-dashboard/issues">File site bug</a> | <a href="https://docs.google.com/document/d/1jrSlM4Yhae7XCJ8BuasWx71CvDEMMbSKbXwx7hoh1Co/edit?pli=1" target="_blank">About</a> | <a href="https://www.google.com/accounts/ServiceLogin?service=ah&passive=true&continue=https://appengine.google.com/_ah/conflogin%3Fcontinue%3Dhttps://www.chromestatus.com/metrics/css/timeline/animated">Login</a> </div> </footer> </app-drawer-layout> <chromedash-toast msg="Welcome to chromestatus.com!"></chromedash-toast> <script> /*! (c) 2017 Copyright (c) 2016 The Google Inc. All rights reserved. (Apache2) */ "use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function e(e,r){for(var n=0;n<r.length;n++){var t=r[n];t.enumerable=t.enumerable||!1,t.configurable=!0,"value"in t&&(t.writable=!0),Object.defineProperty(e,t.key,t)}}return function(r,n,t){return n&&e(r.prototype,n),t&&e(r,t),r}}(),Metric=function(){function e(r){if(_classCallCheck(this,e),!r)throw Error("Please provide a metric name");if(!e.supportsPerfMark&&(console.warn("Timeline won't be marked for \""+r+'".'),!e.supportsPerfNow))throw Error("This library cannot be used in this browser.");this.name=r}return _createClass(e,[{key:"duration",get:function(){var r=this._end-this._start;if(e.supportsPerfMark){var n=performance.getEntriesByName(this.name)[0];n&&"measure"!==n.entryType&&(r=n.duration)}return r||-1}}],[{key:"supportsPerfNow",get:function(){return performance&&performance.now}},{key:"supportsPerfMark",get:function(){return performance&&performance.mark}}]),_createClass(e,[{key:"log",value:function(){return console.info(this.name,this.duration,"ms"),this}},{key:"logAll",value:function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.name;if(e.supportsPerfNow)for(var n=window.performance.getEntriesByName(r),t=0;t<n.length;++t){var a=n[t];console.info(r,a.duration,"ms")}return this}},{key:"start",value:function(){return this._start?(console.warn("Recording already started."),this):(this._start=performance.now(),e.supportsPerfMark&&performance.mark("mark_"+this.name+"_start"),this)}},{key:"end",value:function(){if(this._end)return console.warn("Recording already stopped."),this;if(this._end=performance.now(),e.supportsPerfMark){var r="mark_"+this.name+"_start",n="mark_"+this.name+"_end";performance.mark(n),performance.measure(this.name,r,n)}return this}},{key:"sendToAnalytics",value:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.name,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.duration;return window.ga?n>=0&&ga("send","timing",e,r,n):console.warn("Google Analytics has not been loaded"),this}}]),e}(); </script> <script> document.addEventListener('WebComponentsReady', function(e) { var timeline = $('chromedash-feature-timeline'); timeline.props = [[469,"alias-epub-caption-side"],[470,"alias-epub-text-combine"],[471,"alias-epub-text-emphasis"],[472,"alias-epub-text-emphasis-color"],[473,"alias-epub-text-emphasis-style"],[474,"alias-epub-text-orientation"],[475,"alias-epub-text-transform"],[476,"alias-epub-word-break"],[477,"alias-epub-writing-mode"],[478,"alias-webkit-align-content"],[479,"alias-webkit-align-items"],[480,"alias-webkit-align-self"],[166,"alias-webkit-animation"],[167,"alias-webkit-animation-delay"],[169,"alias-webkit-animation-duration"],[170,"alias-webkit-animation-fill-mode"],[171,"alias-webkit-animation-iteration-count"],[172,"alias-webkit-animation-name"],[173,"alias-webkit-animation-play-state"],[174,"alias-webkit-animation-timing-function"],[177,"alias-webkit-backface-visibility"],[181,"alias-webkit-background-size"],[481,"alias-webkit-border-bottom-left-radius"],[482,"alias-webkit-border-bottom-right-radius"],[197,"alias-webkit-border-radius"],[483,"alias-webkit-border-top-left-radius"],[484,"alias-webkit-border-top-right-radius"],[212,"alias-webkit-box-shadow"],[485,"alias-webkit-box-sizing"],[218,"alias-webkit-column-count"],[219,"alias-webkit-column-gap"],[221,"alias-webkit-column-rule"],[222,"alias-webkit-column-rule-color"],[223,"alias-webkit-column-rule-style"],[224,"alias-webkit-column-rule-width"],[225,"alias-webkit-column-span"],[226,"alias-webkit-column-width"],[227,"alias-webkit-columns"],[486,"alias-webkit-flex"],[487,"alias-webkit-flex-basis"],[488,"alias-webkit-flex-direction"],[489,"alias-webkit-flex-flow"],[490,"alias-webkit-flex-grow"],[491,"alias-webkit-flex-shrink"],[492,"alias-webkit-flex-wrap"],[493,"alias-webkit-justify-content"],[494,"alias-webkit-opacity"],[495,"alias-webkit-order"],[308,"alias-webkit-perspective"],[309,"alias-webkit-perspective-origin"],[496,"alias-webkit-shape-image-threshold"],[497,"alias-webkit-shape-margin"],[498,"alias-webkit-shape-outside"],[537,"alias-webkit-text-size-adjust"],[326,"alias-webkit-transform"],[327,"alias-webkit-transform-origin"],[331,"alias-webkit-transform-style"],[332,"alias-webkit-transition"],[333,"alias-webkit-transition-delay"],[334,"alias-webkit-transition-duration"],[335,"alias-webkit-transition-property"],[336,"alias-webkit-transition-timing-function"],[230,"align-content"],[231,"align-items"],[232,"align-self"],[386,"alignment-baseline"],[454,"all"],[424,"animation"],[425,"animation-delay"],[426,"animation-direction"],[427,"animation-duration"],[428,"animation-fill-mode"],[429,"animation-iteration-count"],[430,"animation-name"],[431,"animation-play-state"],[432,"animation-timing-function"],[532,"apply-at-rule"],[508,"backdrop-filter"],[451,"backface-visibility"],[21,"background"],[22,"background-attachment"],[419,"background-blend-mode"],[23,"background-clip"],[24,"background-color"],[25,"background-image"],[26,"background-origin"],[27,"background-position"],[28,"background-position-x"],[29,"background-position-y"],[30,"background-repeat"],[31,"background-repeat-x"],[32,"background-repeat-y"],[33,"background-size"],[387,"baseline-shift"],[551,"block-size"],[34,"border"],[35,"border-bottom"],[36,"border-bottom-color"],[37,"border-bottom-left-radius"],[38,"border-bottom-right-radius"],[39,"border-bottom-style"],[40,"border-bottom-width"],[41,"border-collapse"],[42,"border-color"],[43,"border-image"],[44,"border-image-outset"],[45,"border-image-repeat"],[46,"border-image-slice"],[47,"border-image-source"],[48,"border-image-width"],[49,"border-left"],[50,"border-left-color"],[51,"border-left-style"],[52,"border-left-width"],[53,"border-radius"],[54,"border-right"],[55,"border-right-color"],[56,"border-right-style"],[57,"border-right-width"],[58,"border-spacing"],[59,"border-style"],[60,"border-top"],[61,"border-top-color"],[62,"border-top-left-radius"],[63,"border-top-right-radius"],[64,"border-top-style"],[65,"border-top-width"],[66,"border-width"],[67,"bottom"],[68,"box-shadow"],[69,"box-sizing"],[520,"break-after"],[521,"break-before"],[522,"break-inside"],[416,"buffered-rendering"],[70,"caption-side"],[547,"caret-color"],[71,"clear"],[72,"clip"],[355,"clip-path"],[356,"clip-rule"],[2,"color"],[365,"color-interpolation"],[366,"color-interpolation-filters"],[367,"color-profile"],[368,"color-rendering"],[523,"column-count"],[440,"column-fill"],[524,"column-gap"],[525,"column-rule"],[526,"column-rule-color"],[527,"column-rule-style"],[528,"column-rule-width"],[529,"column-span"],[530,"column-width"],[531,"columns"],[517,"contain"],[74,"content"],[75,"counter-increment"],[76,"counter-reset"],[77,"cursor"],[466,"cx"],[467,"cy"],[518,"d"],[3,"direction"],[4,"display"],[388,"dominant-baseline"],[78,"empty-cells"],[358,"enable-background"],[369,"fill"],[370,"fill-opacity"],[371,"fill-rule"],[359,"filter"],[233,"flex"],[234,"flex-basis"],[235,"flex-direction"],[236,"flex-flow"],[237,"flex-grow"],[238,"flex-shrink"],[239,"flex-wrap"],[79,"float"],[360,"flood-color"],[361,"flood-opacity"],[5,"font"],[516,"font-display"],[6,"font-family"],[514,"font-feature-settings"],[13,"font-kerning"],[7,"font-size"],[465,"font-size-adjust"],[80,"font-stretch"],[8,"font-style"],[9,"font-variant"],[533,"font-variant-caps"],[15,"font-variant-ligatures"],[535,"font-variant-numeric"],[549,"font-variation-settings"],[10,"font-weight"],[389,"glyph-orientation-horizontal"],[390,"glyph-orientation-vertical"],[453,"grid"],[422,"grid-area"],[418,"grid-auto-columns"],[250,"grid-auto-flow"],[417,"grid-auto-rows"],[248,"grid-column"],[245,"grid-column-end"],[511,"grid-column-gap"],[244,"grid-column-start"],[513,"grid-gap"],[249,"grid-row"],[247,"grid-row-end"],[512,"grid-row-gap"],[246,"grid-row-start"],[452,"grid-template"],[423,"grid-template-areas"],[242,"grid-template-columns"],[243,"grid-template-rows"],[81,"height"],[534,"hyphens"],[397,"image-orientation"],[507,"image-orientation"],[82,"image-rendering"],[398,"image-resolution"],[550,"inline-size"],[438,"internal-callback"],[436,"isolation"],[240,"justify-content"],[455,"justify-items"],[443,"justify-self"],[391,"kerning"],[83,"left"],[84,"letter-spacing"],[362,"lighting-color"],[556,"line-break"],[20,"line-height"],[85,"list-style"],[86,"list-style-image"],[87,"list-style-position"],[88,"list-style-type"],[89,"margin"],[90,"margin-bottom"],[91,"margin-left"],[92,"margin-right"],[93,"margin-top"],[372,"marker"],[373,"marker-end"],[374,"marker-mid"],[375,"marker-start"],[357,"mask"],[435,"mask-source-type"],[376,"mask-type"],[555,"max-block-size"],[94,"max-height"],[554,"max-inline-size"],[95,"max-width"],[406,"max-zoom"],[553,"min-block-size"],[96,"min-height"],[552,"min-inline-size"],[97,"min-width"],[407,"min-zoom"],[420,"mix-blend-mode"],[460,"motion"],[458,"motion-offset"],[457,"motion-path"],[459,"motion-rotation"],[433,"object-fit"],[437,"object-position"],[543,"offset"],[544,"offset-anchor"],[540,"offset-distance"],[541,"offset-path"],[545,"offset-position"],[548,"offset-rotate"],[542,"offset-rotation"],[98,"opacity"],[303,"order"],[408,"orientation"],[99,"orphans"],[100,"outline"],[101,"outline-color"],[102,"outline-offset"],[103,"outline-style"],[104,"outline-width"],[105,"overflow"],[538,"overflow-anchor"],[106,"overflow-wrap"],[107,"overflow-x"],[108,"overflow-y"],[109,"padding"],[110,"padding-bottom"],[111,"padding-left"],[112,"padding-right"],[113,"padding-top"],[114,"page"],[115,"page-break-after"],[116,"page-break-before"],[117,"page-break-inside"],[434,"paint-order"],[449,"perspective"],[450,"perspective-origin"],[557,"place-content"],[558,"place-items"],[118,"pointer-events"],[119,"position"],[120,"quotes"],[468,"r"],[121,"resize"],[122,"right"],[505,"rotate"],[463,"rx"],[464,"ry"],[506,"scale"],[444,"scroll-behavior"],[456,"scroll-blocks-on"],[502,"scroll-snap-coordinate"],[503,"scroll-snap-destination"],[500,"scroll-snap-points-x"],[501,"scroll-snap-points-y"],[499,"scroll-snap-type"],[439,"shape-image-threshold"],[346,"shape-inside"],[348,"shape-margin"],[347,"shape-outside"],[349,"shape-padding"],[377,"shape-rendering"],[123,"size"],[519,"snap-height"],[125,"speak"],[124,"src"],[363,"stop-color"],[364,"stop-opacity"],[378,"stroke"],[379,"stroke-dasharray"],[380,"stroke-dashoffset"],[381,"stroke-linecap"],[382,"stroke-linejoin"],[383,"stroke-miterlimit"],[384,"stroke-opacity"],[385,"stroke-width"],[127,"tab-size"],[126,"table-layout"],[128,"text-align"],[404,"text-align-last"],[392,"text-anchor"],[509,"text-combine-upright"],[129,"text-decoration"],[403,"text-decoration-color"],[401,"text-decoration-line"],[546,"text-decoration-skip"],[402,"text-decoration-style"],[130,"text-indent"],[441,"text-justify"],[131,"text-line-through"],[132,"text-line-through-color"],[133,"text-line-through-mode"],[134,"text-line-through-style"],[135,"text-line-through-width"],[510,"text-orientation"],[136,"text-overflow"],[137,"text-overline"],[138,"text-overline-color"],[139,"text-overline-mode"],[140,"text-overline-style"],[141,"text-overline-width"],[11,"text-rendering"],[142,"text-shadow"],[536,"text-size-adjust"],[143,"text-transform"],[144,"text-underline"],[145,"text-underline-color"],[146,"text-underline-mode"],[405,"text-underline-position"],[147,"text-underline-style"],[148,"text-underline-width"],[149,"top"],[421,"touch-action"],[442,"touch-action-delay"],[446,"transform"],[559,"transform-box"],[447,"transform-origin"],[448,"transform-style"],[150,"transition"],[151,"transition-delay"],[152,"transition-duration"],[153,"transition-property"],[154,"transition-timing-function"],[504,"translate"],[155,"unicode-bidi"],[156,"unicode-range"],[539,"user-select"],[409,"user-zoom"],[515,"variable"],[393,"vector-effect"],[157,"vertical-align"],[158,"visibility"],[168,"webkit-animation-direction"],[354,"webkit-app-region"],[412,"webkit-app-region"],[175,"webkit-appearance"],[176,"webkit-aspect-ratio"],[400,"webkit-background-blend-mode"],[178,"webkit-background-clip"],[179,"webkit-background-composite"],[180,"webkit-background-origin"],[399,"webkit-blend-mode"],[182,"webkit-border-after"],[183,"webkit-border-after-color"],[184,"webkit-border-after-style"],[185,"webkit-border-after-width"],[186,"webkit-border-before"],[187,"webkit-border-before-color"],[188,"webkit-border-before-style"],[189,"webkit-border-before-width"],[190,"webkit-border-end"],[191,"webkit-border-end-color"],[192,"webkit-border-end-style"],[193,"webkit-border-end-width"],[194,"webkit-border-fit"],[195,"webkit-border-horizontal-spacing"],[196,"webkit-border-image"],[198,"webkit-border-start"],[199,"webkit-border-start-color"],[200,"webkit-border-start-style"],[201,"webkit-border-start-width"],[202,"webkit-border-vertical-spacing"],[203,"webkit-box-align"],[228,"webkit-box-decoration-break"],[414,"webkit-box-decoration-break"],[204,"webkit-box-direction"],[205,"webkit-box-flex"],[206,"webkit-box-flex-group"],[207,"webkit-box-lines"],[208,"webkit-box-ordinal-group"],[209,"webkit-box-orient"],[210,"webkit-box-pack"],[211,"webkit-box-reflect"],[73,"webkit-clip-path"],[213,"webkit-color-correction"],[214,"webkit-column-axis"],[215,"webkit-column-break-after"],[216,"webkit-column-break-before"],[217,"webkit-column-break-inside"],[220,"webkit-column-progression"],[396,"webkit-cursor-visibility"],[410,"webkit-dashboard-region"],[229,"webkit-filter"],[413,"webkit-filter"],[341,"webkit-flow-from"],[340,"webkit-flow-into"],[12,"webkit-font-feature-settings"],[241,"webkit-font-size-delta"],[14,"webkit-font-smoothing"],[251,"webkit-highlight"],[252,"webkit-hyphenate-character"],[253,"webkit-hyphenate-limit-after"],[254,"webkit-hyphenate-limit-before"],[255,"webkit-hyphenate-limit-lines"],[256,"webkit-hyphens"],[258,"webkit-line-align"],[257,"webkit-line-box-contain"],[259,"webkit-line-break"],[260,"webkit-line-clamp"],[261,"webkit-line-grid"],[262,"webkit-line-snap"],[16,"webkit-locale"],[264,"webkit-logical-height"],[263,"webkit-logical-width"],[270,"webkit-margin-after"],[265,"webkit-margin-after-collapse"],[271,"webkit-margin-before"],[266,"webkit-margin-before-collapse"],[267,"webkit-margin-bottom-collapse"],[269,"webkit-margin-collapse"],[272,"webkit-margin-end"],[273,"webkit-margin-start"],[268,"webkit-margin-top-collapse"],[274,"webkit-marquee"],[275,"webkit-marquee-direction"],[276,"webkit-marquee-increment"],[277,"webkit-marquee-repetition"],[278,"webkit-marquee-speed"],[279,"webkit-marquee-style"],[280,"webkit-mask"],[281,"webkit-mask-box-image"],[282,"webkit-mask-box-image-outset"],[283,"webkit-mask-box-image-repeat"],[284,"webkit-mask-box-image-slice"],[285,"webkit-mask-box-image-source"],[286,"webkit-mask-box-image-width"],[287,"webkit-mask-clip"],[288,"webkit-mask-composite"],[289,"webkit-mask-image"],[290,"webkit-mask-origin"],[291,"webkit-mask-position"],[292,"webkit-mask-position-x"],[293,"webkit-mask-position-y"],[294,"webkit-mask-repeat"],[295,"webkit-mask-repeat-x"],[296,"webkit-mask-repeat-y"],[297,"webkit-mask-size"],[299,"webkit-max-logical-height"],[298,"webkit-max-logical-width"],[301,"webkit-min-logical-height"],[300,"webkit-min-logical-width"],[302,"webkit-nbsp-mode"],[411,"webkit-overflow-scrolling"],[304,"webkit-padding-after"],[305,"webkit-padding-before"],[306,"webkit-padding-end"],[307,"webkit-padding-start"],[310,"webkit-perspective-origin-x"],[311,"webkit-perspective-origin-y"],[312,"webkit-print-color-adjust"],[343,"webkit-region-break-after"],[344,"webkit-region-break-before"],[345,"webkit-region-break-inside"],[342,"webkit-region-fragment"],[313,"webkit-rtl-ordering"],[314,"webkit-ruby-position"],[395,"webkit-svg-shadow"],[353,"webkit-tap-highlight-color"],[415,"webkit-tap-highlight-color"],[315,"webkit-text-combine"],[316,"webkit-text-decorations-in-effect"],[317,"webkit-text-emphasis"],[318,"webkit-text-emphasis-color"],[319,"webkit-text-emphasis-position"],[320,"webkit-text-emphasis-style"],[321,"webkit-text-fill-color"],[17,"webkit-text-orientation"],[322,"webkit-text-security"],[323,"webkit-text-stroke"],[324,"webkit-text-stroke-color"],[325,"webkit-text-stroke-width"],[328,"webkit-transform-origin-x"],[329,"webkit-transform-origin-y"],[330,"webkit-transform-origin-z"],[337,"webkit-user-drag"],[338,"webkit-user-modify"],[339,"webkit-user-select"],[352,"webkit-wrap"],[350,"webkit-wrap-flow"],[351,"webkit-wrap-through"],[18,"webkit-writing-mode"],[159,"white-space"],[160,"widows"],[161,"width"],[445,"will-change"],[162,"word-break"],[163,"word-spacing"],[164,"word-wrap"],[394,"writing-mode"],[461,"x"],[462,"y"],[165,"z-index"],[19,"zoom"]]; document.body.classList.remove('loading'); window.addEventListener('popstate', function(e) { if (e.state) { timeline.selectedBucketId = e.state.id; } }); }); </script> <script> /*! (c) 2017 Copyright (c) 2016 The Google Inc. All rights reserved. (Apache2) */ "use strict";!function(e){function r(){return caches.keys().then(function(e){var r=0;return Promise.all(e.map(function(e){if(e.includes("sw-precache"))return caches.open(e).then(function(e){return e.keys().then(function(n){return Promise.all(n.map(function(n){return e.match(n).then(function(e){return e.arrayBuffer()}).then(function(e){r+=e.byteLength})}))})})})).then(function(){return r})["catch"](function(){})})}function n(){"serviceWorker"in navigator&&navigator.serviceWorker.register("/service-worker.js").then(function(e){e.onupdatefound=function(){var n=e.installing;n.onstatechange=function(){switch(n.state){case"installed":t&&!navigator.serviceWorker.controller&&o.then(r().then(function(e){var r=Math.round(e/1e3);console.info("[ServiceWorker] precached",r,"KB");var n=new Metric("sw_precache");n.sendToAnalytics("service worker","precache size",e),t.showMessage("This site is cached ("+r+"KB). Ready to use offline!")}));break;case"redundant":throw Error("The installing service worker became redundant.")}}}})["catch"](function(e){console.error("Error during service worker registration:",e)})}var t=document.querySelector("chromedash-toast"),o=new Promise(function(e,r){return window.asyncImportsLoadPromise?window.asyncImportsLoadPromise.then(e,r):void e()});window.asyncImportsLoadPromise||n(),navigator.serviceWorker&&navigator.serviceWorker.controller&&(navigator.serviceWorker.controller.onstatechange=function(e){if("redundant"===e.target.state){var r=function(){window.location.reload()};t?o.then(function(){t.showMessage("A new version of this app is available.","Refresh",r,-1)}):r()}}),e.registerServiceWorker=n}(window); // https://gist.github.com/ebidel/1d5ede1e35b6f426a2a7 function lazyLoadWCPolyfillsIfNecessary() { function onload() { // For native Imports, manually fire WCR so user code // can use the same code path for native and polyfill'd imports. if (!('HTMLImports' in window)) { document.body.dispatchEvent( new CustomEvent('WebComponentsReady', {bubbles: true})); } } var webComponentsSupported = ('registerElement' in document && 'import' in document.createElement('link') && 'content' in document.createElement('template')); if (!webComponentsSupported) { var script = document.createElement('script'); script.async = true; script.src = '/static/bower_components/webcomponentsjs/webcomponents-lite.min.js'; script.onload = onload; document.head.appendChild(script); } else { onload(); } } var button = document.querySelector('app-header paper-menu-button'); button.addEventListener('click', function lazyHandler(e) { this.removeEventListener('click', lazyHandler); var url = '/static/elements/paper-menu-button.vulcanize.html'; Polymer.Base.importHref(url, function() { button.contentElement.hidden = false; button.open(); }, null, true); }); // Google Analytics (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-39048143-1', 'auto'); ga('send', 'pageview'); // End Google Analytics lazyLoadWCPolyfillsIfNecessary(); </script> </body> </html>
pie6k / Use MethodHook for creating callbacks that behave like class methods - function keeps the same reference during entire component lifecycle and always have access to 'fresh' variables from last render.
HowProgrammingWorks / CallbacksCallbacks, Listeners and Events
feross / Memo Async LruMemoize Node.js style callback-last functions, using an in-memory LRU store
HenrikJoreteg / Native Promisify If PresentReturn a promise from a callback-as-last-argument function using native a Promise, but only if native Promises exist.
ripred / ButtonGesturesUse a single push button for up to 6 different functions! Button gesture combinations of single, double, and triple-tap along with a long or short hold on the last press make it easy! Functions can also be pre-registered for callback for the gesture that you want. Even easier!
sn0112358 / Angular Directive ProjectAngular-Directive-Project Directives range from very basic to extremely complex. This project will build up to some somewhat difficult directives. Keep in mind that the format we're learning for directives is the same format used to build some extremely complex things in angular. Using directives often and well is one way to show you're a talented developer. Starting Out We've included only a few things for you to begin with. index.html, app.js, styles.css. At this point the best way to get more comfortable with angular is to initialize an app without relying heavily on boilerplate code (reusable code that starts out your projects for you). You'll notice that in the index.html we've included the angular-route CDN. Yes, we'll be using angular's router here. Put an ng-view into your index.html. In your app.js set up a config and set up our first route for when a user is at the '/home' url. If you're having trouble remembering how to set up the router go look at how you set up the router on the previous project. One way these projects will be beneficial to you is allowing you to look back at something *you** did and seeing how you got that something to work.* You may also want add an otherwise that defaults to /home. Create a controller and a template file for this route in your app folder. Don't forget to include the controller as a script in your index.html Check that everything is hooked up correctly. Try adding a div with some text in your home template just to make sure it's showing up. Once you've got that going you're ready to start on some directives. Now let's make our directive. We'll start with a simple one that we can use to display information passed to it. Step 1. Start your directive Woot. When you're initializing your directive just remember that it works very similarly to how you start up a controller or a service. It can also be very helpful to think of your directive as a route. Create your directive. You'll use the directive method on your angular module. It takes two arguments, the name string and the callback function, which will return the object that represents your directive. When naming your directive give it a name with two words; dirDisplay would be nice, but anything works. Just remember it's best practice to give a directive a camel case name so that it's clear in your html what it is. Also we're going to need a template html for our directive. We could do it inline, but let's make another file instead. Just name it something that makes sense for the name of your directive and put it in the same directory as your directive file. For your template just make a <div> and inside a <h1> tag that says User. Now in your home route html add in your directive. It will look like this if you named it dirDisplay: <dir-display></dir-display> Start up your app and go to the home route. Check and make sure you see User where your directive was placed. If you're not seeing it at this point it could mean a few things. Here's some more common issues. You didn't link your directive in your index as a script. Your name for your directive doesn't match the name in your html. Remember camel case becomes snake case so myDirective becomes <my-directive></my-directive>. You're file path to your html template is wrong. You have to think of file paths in angular as relative to the index. Here's some code to see just for this part, and just for the directive's js file. var app = angular.module('directivePractice'); app.directive('dirDisplay', function(){ return { templateUrl: 'app/directives/dirDisplay.html' }; }); What we're returning is the directive object. You won't see anymore code in this tutorial so it's important you get things working right and refer back to what you've already done to advance from now on. Step 2. Advancing directives Your directive should be loaded up now, but it's not really doing much. Let's make it better. In your home controller. Make a variable on your $scope called user. Set it's value to { name: "Geoff McMammy", age: 43, email: "geofdude@gmail.com" } Now inside your directive's html specifically inside the <h3> tags display our new user's name. Then inside maybe some <h4> tags display his email and age. This is going to work exactly the same as if it was just inside your home controller. Reload the page and make sure it works. This is still very cosmetic and really not all that useful. It needs functionality. Add into your directive's object the link property. The link property's value is a function definition that takes (generally) three parameters. scope, element, and attributes. Unlike in other places with angular injection these parameter names don't carry meaning. The first parameter will always represent your $scope for that directive, the second will always be the element that wraps your whole directive, and the third will always be an object containing all the properties and values of the attributes on your directive in the dom. Try the following to get a feel for all three. Add two attributes to your directive in your html. Like this - <dir-display test="myTest" my-check="checkItOut"></dir-display> Now in the link property you've added console.log the three parameters in the function. You'll see an object for scope that should look identical to the $scope of your html function. For element you'll see an object the represents the DOM wrapper for your directive. For attributes you'll see an object that will look like this: { test: "myTest", myCheck: "checkItOut" } An important thing to notice is how it has again converted snake case to camel case for you. my-check became myCheck. Don't forget this. You'll run into this issue one day. It counts for both attributes and directive names. To feel some of what the link function could do let's try this. Add a ng-show to both the email and age wrappers. This should be familiar to you. Now inside your link function add a click event listener to your element property. It's going to look just like jQuery. element.on('click', function(){ }) Inside the click listener's callback add a toggle for the ng-show property you passed in. Along with a console.log to make sure things are connecting when you click. Try it out. Don't call for a mentor when it doesn't work. Let's talk about that first. You should see the console.log firing, but why isn't it toggling. This is going to be a common problem when working with the link function and event listeners. What we have here is an angular digest problem. The value is changing on the scope object, but the change isn't being reflected by our DOM. That's because angular isn't aware of the change yet. Anytime we cause an event to happen using something like jQuery or even angular's jQLite we need to let angular know that we've made a change. Add this line of code in place of your console.log, scope.$apply(). Now try it out. It should be working now, so if you're still having issues it's time to debug. What we've done is forced angular to run it's digest cycle. This is where angular checks the scope object for changes and then applies those to the DOM. This is another good lesson to learn for later. You'll most likely hit this when making changes to your element using event listeners. Step 3. Directive's re-usability. Now our directive has some extremely basic functionality. One of a directive's greatest advantages though is its ability to be placed anywhere and still be functional. Let's say instead we had a list of users instead of just one. Change the $scope property in your home controller to be users and give it this array as its value: [ { name: "Geoff McMammy", age: 43, email: "geofdude@gmail.com", city: "Provo" }, { name: "Frederick Deeder", age: 26, email: "fredeed@gmail.com", city: "Austin" }, { name: "Spencer Rentz", age: 35, email: "spencerrentz@gmail.com", city: "Sacramento" }, { name: "Geddup Ngo", age: 43, email: "geddupngo@gmail.com", city: "Orlando" }, { name: "Donst Opbie Leevin", age: 67, email: "gernee@gmail.com", city: "Phoenix" } ] Now in your home HTML add a ng-repeat to the directive call. Tell it to repeat for each user in users. Reload your page. It's working! But why? How does each directive instance know what information to display? In the link function console.log the scope parameter. Make sure it's outside of your click listener. You'll see five print outs in your console. Open up any one of them and look to the bottom. Open up the user property. It's exactly what we would want! But again why would that be the case? Don't get too caught up in this next bit if it's too hard to understand, but the ng-repeat is essentially making new tiny scope objects for each individual user in our users array. Now each of our directives is still getting a user property on the scope object just like the directive wanted in the beginning. Woot. Step 4. Ramp it up with Isolate Scope. Directives can do so much more. So let's make that happen. That means we should make.... a new directive!!! This directive's purpose will be to display a selected User and the weather in his/her/its location. Link it up just like the last one. Create a js file for our directive and name it dirWeather. Make an html file named dirWeather.html. Link it up in your index.html and add the template to your new directive object. In your directive's template give it an <h3> tag that says Weather just so we can know it's working. Above your ng-repeat on dirDisplay add your new dirWeather directive. If it's not working check the instructions above as to some common reasons why before asking a mentor for help. If you're seeing the Weather text on your page then we're ready to try out the dreaded Isolate Scope. The isolate scope object is one of the stranger API's in angular. I'm sorry but it is. Just refer to this for now. scope: { string: '@', link: '=', func: '&' } The properties on the scope object represent the attributes on the directive in the html. Our example scope object here would look something like this in the html. <example-directive string="a string" link="user" func="updateUser()"></example-directive> The hard part here is the @, =, and &. They each have very important and distinct meanings. @ says take in my attribute value as a string. = says take in my attribute value as a two-way bound variable from the parent scope. & says take in my attribute value as a reference to a function on the parent scope. It's also critical to point out that once you add a scope object you have no isolated your directive's scope. Meaning, aside from the values passed in through attributes, this directive has no connection to the $scope of its parent. That being said let's isolate our directive's scope. :worried: Add the scope property to your dirWeather. Give it the value of an object with a property of currentUser whose value is '='. Remember in your html this will look like current-user. This is the third time I've said so don't expect it again. This means that whatever comes into the currentUser attribute is going to be a value of the parent's scope object. For now test this out by passing in users[0]. Find a way to show that users information inside your dirWeather's html. Remember inside your directive now the user is represented by currentUser. Step 5. &? &!? The '=' value on your scope object has created a two-way binding between users[0] and currentUser. Now let's try out the '&'. On your home controller add a function called getWeather. It takes one parameter called city. This function will make a call to a service so we'll need to create that. Make a weather service. Name it something cool and creative like weatherService. Inside the weather service make a function called getWeather that also takes one parameter, city. Make an $http get to this url - 'http://api.openweathermap.org/data/2.5/weather?q=' After the q= add on the city parameter. If you want you can test this out in postman. See what kind of data you get back. If it's the weather of that city then... you win! Use $q to return a promise that only resolves with the data you want. Temperature (preferably not in Kelvin) and the weather description. Use console.log on the data coming from the $http request to get to what you want. You'll need to add both on an object that you resolve your new promise with. On your home controller have it return the result of invoking the get getWeather function on the service. You should be returning a promise. Now in your home route's HTML pass in the getWeather function to the dirWeather directive through an attribute called weather-call. Add the attribute to your isolate scope object. That was a lot of linking, but let's walk through it. Your controller has a function linked to the service, which is in turn linked to your directive. So if you run the weatherCall function in your directive it will go through your controller to your service and then back. Now things get a little bit tricky. Angular's way of passing along arguments through a directive to your controller are tricky, but once you understand how to do it, it's not hard. I'm going to give an example here of how it works. <my-directive pass-func="callFunc(data)"></my-directive> Here's how it would look in your HTML. But where's the data supposed to be coming from? It seems that you'd rather be able to pass in data from your directive. Well you still can, you just have to essentially tell angular what do use as an argument to replace data when it calls that function in your controller. The actualy function call inside the directive will look like this. $scope.passFunc({data: wantedData}) So what you'll do is pass in an object where the property name is what the argument is named in the HTML where you call the directive. That might sound confusing, but just look at the two code blocks above for a pattern. Note that pass-func becomes $scope.passFunc and data is being replaced with wantedData with the {data: wantedData} object. In our directive we want to replace city in the attribute call, for something else inside the directive. You'll follow the same pattern as above. For now let's get things set up for that function call. Add to the dirWeather directive object a property called controller. It's value will be a function. Yes, this is a controller specifically for your one directive. It works the same as any other controller, except you don't give it a name. It's $scope object will only be accessible within an instance of your directive. Don't forget to inject $scope in the function. Inside your controller function run the weatherCall function with the city property from the currentUser on your $scope. Here's where you need to make sure you've passed in a city argument in the attribute function call, and then replace that with your currentUser's city using an object with a city property. The function call should return a promise, so call .then afterward and add the data onto your $scope to display both the weather and temperature of the currentUser's city. The properties can be named whatever makes sense to you. You may also want to find a way to get rid of all the decimal places on your temperature. Now you should have everything hooked up so it shows Geoff's data and the weather data for Provo. But is that good enough? Step 6. Ramping up our ramp up. Now let's change this so it shows the weather data for whichever user we select. We're going to need to use '&' again. Make a function on the home controller that takes in a parameter and sets a property on the $scope to be that parameter. Maybe you see where this is going. We want to get this function into our dirDisplay controller. But in order to do that we need to isolate dirDisplay's scope. This also means we need to pass in each individual user through the scope object as well. To make it easier on ourselves, let's pass the current user from our ng-repeat into our directive through a user attribute. This way we can leave our two-way bindings as they are. Also pass our new function that sets our current user from our home controller into our directive through a setUser attribute. You'll need to add an argument in there again. Go with user. Your scope object in dirDisplay should have two properties. setUser with the value of '&' and user with the value of '='. As before we're going to need to do some tricky stuff to get our argument back to our controller. Call the setUser function inside our click event listener and pass in an object the sets our user argument to be the user on our directive's scope object. If you've forgotten this part go back up and take a look at how you did it before or the example in this README. Whatever user you click on now should show up in the dirWeather directive as the current user. But we're missing one thing, we want to be able to see the weather for that user too. We'll have to do one more thing that will seem a little bit tricky at first, but it's good to learn if you don't know it already since it's actually used quite frequently. We need to step up a change listener on our currentUser in the dirWeather directive. We'll use angular's $watch functionality. $watch is a method on your $scope that will watch for changes in a variable you give it. It works in two ways. $scope.$watch('property', function(value){ console.log("When $scope.property changes its new value is: ", value) }); And $scope.$watch(function(){ return myVar }, function(value){ console.log("When myVar changes its new value is: ", value); }); Remove the immediate function call that we have in there now. Maybe just comment it out for now because we'll use it in a bit. Now call the $watch method on your scope and have it watch currentUser. Either way of using $watch is fine. Have its callback run the $scope.weatherCall function just like you had it before. One thing to note is that $scope.$watch will always run once to begin with. Since that's what we want here it's great, but just be aware of that. If you've reached this point congratulate yourself. You've messed with some serious stuff today, namely directives. There are still a lot of things about directives that we can't possibly cover in a single project. If you like what we've done so far then you're in a good place to keep going. A developer who understands directives well can build a really clean looking code base. Just look at your home.html. It could have just two lines in it. If you're feeling good move on now to Step 7. Step 7. Finishing touches Try to work out these problems on your own. There should be a way to let the user know that the weather data is loading. Something that appears while our $http request is retrieving our data. The $http request shouldn't fire on both opening and closing a user's information. A color change for the currently active user would be nicer than showing that user's info inside the dirWeather modal. Or at least less redundant. Whatever else you want. We still haven't explored transclusion and ng-transclude so give that a try if you're feeling adventurous. Just know that it's a way for deciding where to put the HTML child elements of a directive. It's cool stuff that can involve some criss-crossing of scopes.
ozanhalis / Hi// ==UserScript== // @name CS GO LOUNGE BOT-Ozan Halis // @namespace http://csgolounge.com/ // @version 0.6.6 // @description Cs Go Lounge Hızlı BOT // @match http://csgolounge.com/* // @match http://dota2lounge.com/* // @updateURL http://ncla.me/csgl3000/csgl3000.meta.js // @downloadURL http://ncla.me/csgl3000/csgl3000.user.js // @require http://code.jquery.com/jquery-2.1.1.js // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_xmlhttpRequest // @grant GM_addStyle // @copyright iamncla @ GitHub.com // ==/UserScript== /* HELPER FUCNTIONS */ /* Get URL parameter */ function gup(a){a=a.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var b="[\\?&]"+a+"=([^&#]*)",c=new RegExp(b),d=c.exec(window.location.href);return null==d?null:d[1]} /* Get day/month/year */ function getDMY(){var a=new Date;return a.getFullYear()+"/"+(a.getMonth()+1)+"/"+a.getDate()} /* DOM observe */ var observeDOM=function(){var e=window.MutationObserver||window.WebKitMutationObserver,t=window.addEventListener;return function(n,r){if(e){var i=new e(function(e,t){if(e[0].addedNodes.length||e[0].removedNodes.length)r()});i.observe(n,{childList:true,subtree:true})}else if(t){n.addEventListener("DOMNodeInserted",r,false);n.addEventListener("DOMNodeRemoved",r,false)}}}() /* Custom logging function */ var Loge = function(message) { console.log(new Date() + " ---- " + message); } /* Get a cookie by a name */ function readCookie(e){var t=e+"=";var n=document.cookie.split(";");for(var r=0;r<n.length;r++){var i=n[r];while(i.charAt(0)==" ")i=i.substring(1,i.length);if(i.indexOf(t)==0)return i.substring(t.length,i.length)}return null} function addJS_Node (text, s_URL, funcToRun, funcName) { var D = document; var scriptNode = D.createElement ('script'); scriptNode.type = "text/javascript"; if (text) scriptNode.textContent = text; if (s_URL) scriptNode.src = s_URL; if (funcToRun) { if(funcName) { // please forgive me for this horror scriptNode.textContent = funcToRun.toString().replace("function () {", "function " + funcName + "() {"); } else { scriptNode.textContent = '(' + funcToRun.toString() + ')()'; } } var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement; targ.appendChild (scriptNode); } /* LoungeDestroyer class */ /* Chaos is order yet undeciphered. */ /* yaroberto -2 points 5 hours ago dont use shity scripts :) */ if (window.top != window.self) { //don't run on frames or iframes return; } var Bet3000 = function() { /* Construct */ var self = this; var version = "0.6.6"; var versionReleaseDate = "2014.08.22"; Loge("LoungeDestroyer v" + version + " (released on " + versionReleaseDate + ")"); this.betAttempts = 0; this.inventoryAttempts = 0; this.returnAttempts = 0; this.TLS = false; this.profileNumber = null; this.isPlacingBet = false; this.placeBetRetry = false; /* User settings */ this.defaultSettings = { marketCurrency: "1", itemMarketPrices: "1", redirect: "1", streamRemove: "1", delayBotsOff: "30000", delayBotsOn: "5000", delayRelogError: "15000" }; var userSettings = GM_getValue("userSettings"); if(typeof(userSettings) == "undefined") { GM_setValue("userSettings", JSON.stringify(self.defaultSettings)); } this.userSettings = JSON.parse(GM_getValue("userSettings")); this.saveSetting = function(settingName, settingValue) { self.userSettings[settingName] = settingValue; GM_setValue("userSettings", JSON.stringify(self.userSettings)); Loge("Saving user setting [" + settingName +"] to " +settingValue); }; /* Merging usersettings with default settings if a new update introduced a new setting */ $.each(this.defaultSettings, function(index, value) { if (typeof self.userSettings[index] == 'undefined') { self.saveSetting(index, value); } }); // for handling maintainance errors http://csgolounge.com/break and wait.html page if(this.userSettings["redirect"] == "1") { if(document.URL.indexOf("/wait.html") != -1 || document.URL.indexOf("/break") != -1 || document.title == "The page is temporarily unavailable") { window.location = GM_getValue("intendedVisitURL", location.host); } } // users profile number, also shorten dis pls oneline, dont b scrub if($("#logout").length) { self.profileNumber = readCookie("id"); } // ncla pls shorten dis this.appID = "730"; if(window.location.hostname == "dota2lounge.com") { this.appID = "570" } $("a").click(function(e) { if (e.which === 1) { e.preventDefault(); if(self.isPlacingBet) { $(window).unbind('beforeunload'); } // http://stackoverflow.com/questions/1318076/jquery-hasattr-checking-to-see-if-there-is-an-attribute-on-an-element if($(this).is("[href]")) { var url = $(this).attr("href"); GM_setValue("intendedVisitURL", url); window.location = url; } } }); GM_addStyle(".marketPriced .rarity { background: rgba(255, 255, 255, 0.7) !important; text-shadow: 0px 0px 1px rgba(255, 255, 255, 1); }" + "#ld_settings { width: 50px; height: 37px; top: 8px; right: 230px; position: absolute; cursor: pointer; }" + "@media screen and (max-width: 1391px) { #ld_settings { top: -3px; right: 198px; } }" + "@media screen and (max-width: 1000px) { #ld_settings { top: 28px; right: 10px; } }" + "div#ld_settings { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAFpOLgnAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAABgNJREFUeNpi/P//PwMuwMSAB7Agc9p3HFNkYGBYx8DAIF3pYSUG1/n48eP/Mdqy9xgYGHgZGBj0GRgYGBj+//+Pgdu2H334//9/BkayHQQAAAD//8Kpk4kk49p3HEtgePTo0Uw0153///8/A7qTn8HYpFsOAAAA///C61GyAgBvTD1+/HimrKxsOixSGBgYGF58+bFyz8PXOgwMDL8ZGBhCGRgY7Co9rObhtElWVpZRgocjvNLDSoeBgeEaAwPDLgYGhtz2Hcdk6OsnAAAAAP//ItkmJpo7i4mseMEF2nccy2dgYGCu9LDqa99xLJaBgSGO8f///wyPHz++Kysrq4wckUuuPr7EwMDwn4GBgZuBgWEyAwNDbaWHlSiGBjQb1BgYGFYyMDDwVXpYKeP0w+PHjzugzDoGBgY/BgaGT+07jt3DGw/tO469rPSwEoeyVRkYGNQYGBhqh0PEAQAAAP//7JSvS4NhEMc/gtgta+9AxGRW5EAwiNxfsK5h0WTw/AeetL6BA8OY3fSAW33agmFB0HQYFMMwadLyCu9eXsG9QQy7dtwdX7jvj1oy/xNb/EuQ1bqHIaYL4AR4NZW90uwJuAMeTOV0YU5CTGPg2lQuQ0wd4AB4NJVWiOkZOAPWgGAqjTni3b0HHJZ95e6fWZatFHbag6kPgd08ZT/y1XVgB5iYSrNSXb8BqepDTJvACJgVwPZNxX8CaZdj/jtaCnU+mPoV0AVmpnJc8HYE3vJ3NYBtU3mpw0kf2AKOTOW9Yr4B3AC3wL2p9JZmXKi+2C93lQaCKAx/GhWFpLEMRFaJ+g5TSsApgiCKWKdLZeF1OqsdFQvxAawULMQqYRe03X0BiSCIipfKG6iFNmJzApsQhSRWugsDyzkHPub8w/xz4nbFkP/oJ9YPU8AJ0A3MGK2CSE4DY0DRaJVqaSfWDzuNVq9GK0du3r1ILg9kxcw229nJFTBg/TAhj70P64c9gAYcYBVYBh4bXfU1PiGxIyAXje1Wbq6BN5nZHoAO4BzYAsrAEvBktDpoRvhjgfcDTI+my0Af8C4ApEVzwDjwEgU0pUkmk3kGVnq7EkWj1ZDRagS4jZQMAwtGq/3fPsITwKU8xgGy1g8P24WsAetykpLAJzAF3EVqnHpQjfD1Xi6i5+p93/phAdgGBo1W9wItAWkpSwIVo9Xkt8P8T8v1glnXC05dLyg0yJVcLziT/8VqvBVNdoCN6jQb/YxWeeDC+uG8dCJ2xhjyFyBf7Jo9aBRBGIafwIWA6CkoRsTxJ0GMiBi4JgwqiBEGgr2QFBY26hFshAwKEoJOgj8QURDBQkmlJAo2U5wSRUZFxOpAEA/iRfxFEZRTUbG4b8kSTnMI2QPZD6bZ3dndd/b7e9/ZRFz4v1mtFEgKJAXSeMsk+TDnQ46qRLoIeAvcA65Yo5/XMXcHMAQskXmD1uhXDU2/zod+IA98AbLSFfbG1Z7YtT3SGp2Qzt5KX7zAGr09MddyPkxI/xXvy84CWtjAZ6AVGHY+NMeJlPPhHdAGHAaOAS3AOWAz4P5aEGNyV6mWKD4XN4rTGWBkrFjuFer4FTgD3BB+tFdW9pe84LSwvxZgEjgJfABGqSqNGeA4cGA27ZnvGOkGuvs2KXzpzc33le9bgP3AQaqK5VSMn30DlgF3gYdAJ7APWAEcEaKSj+TS+Qz2glJq15++mGlrXTlWLHcAu4EuCVgFrBHXapLxCegAHgP3gaNAc7Rx0cisVZAvk7NGV4CrMqI4WC2u08mMzAvwEdgg8584Hw5Zo180so5E8VOqkQQWSyZ6AOwU4rwwRp6bBNw6YNL5MO58UHV3v7W07Ro2oJQamSPY49aulCoJgCxwHugDLgMD1ujXcm69CCYbxc1m21LgEdBvjX6ZlGtdAy4qpQrOhwzF8iVgj9SOW8DyiPTH0vIzoEd2FUYFUCT2T0vWygK3nQ/XrdHJUWrnw1pgXGpFBbgDDFmjp+qY2y5KR07S7oQcPwV0WaO3JgkkT/X/iNPW6Kf/eI9VImhsA35Ipb9gjf6ZMsQUSAokBZICaaj9HgC1oa+f3fgOHQAAAABJRU5ErkJggg==); }" + "#ld_popup { display: none; width: 280px; height: 380px; background: white; position: fixed; top: 50%; left: 50%; margin-left: -140px; margin-top: -190px; box-shadow: 0px 0px 40px 0px rgba(0, 0, 0, 0.5); z-index: 9001; }" + "#ld_popup .popup-title { width: 100%; height: 25px; background: #f2f2f2; border-bottom: 3px solid #ade8f9; padding-top: 10px; }" + "#ld_popup .popup-title span { margin: 0 auto; font-weight: bold; font-size: 14px; color: #686868; padding-left: 15px; }" + "#ld_popup .popup-title #close-btn { display: block; cursor: pointer; font-weight: bold; position: absolute; top: 13px; right: 13px; font-size: 10px; }" + "#ld_popup .ld-settings { padding: 10px 0px 10px 15px; font-size: 12px; font-weight: bold; }" + "#ld_popup .ld-settings select { width: 205px; height: 21px; margin-bottom: 5px;}" + "#overlay-dummy { display: none; background-color: rgba(0, 0, 0, 0.3); position: fixed; width: 100%; height: 100%; z-index: 9000; }" + "#ld_popup .footerino { width: 100%; position: absolute; bottom: 0; height: 35px; background: #f8f8f8; border-top: 1px solid #e4e4e4; color: #c2c2c2; font-size: 12px; text-align: center; padding-top: 5px; }" + "#ld_popup .footerino a { color: #a0a0a0; }" + "#ld_popup .footerino a:hover { text-decoration: underline; }" + ".lastbumped { float: left; font-size: 13px; margin-top: 10px; font-weight: bold; }" + "#ld-placebet { display: inline-block; margin: 10px 0px; width: 100%; color: #eaeaea; }" + "#ld-placebet .wrapperino { margin: 13px; }" + "#ld-placebet .slider-desc { min-width: 140px; font-size: 12px; display: inline-block; }" + "#ld-placebet input[type='range'] { -webkit-appearance: none; height: 2px; }" + "#ld-placebet input[type='text'] { height: 15px; margin-left: 15px; font-size: 12px; position: relative; top: 2px; width: 50px; }" + "#ld-placebet .setting-block { height: 25px; }"); this.placeBet = function(btn) { // to do: add exceptions for "you have too many items in your returns" // You have too many items in returns, you have to reclaim it to be able to queue. // Due to extensive load, queue is disabled for about 5 minutes. // You have to relog in order to place a bet. if(!this.checkBetRequirements()) return false; if(self.isPlacingBet) return false; self.isPlacingBet = true; unsafeWindow.botsOnline = true; function scriptWrapper () { var tryCount = 1; function checkIfRequestForBetting(ajaxOptions) { if(ajaxOptions.hasOwnProperty("data")) { return (ajaxOptions.data.indexOf("&on=") != -1); } else { return false; } } $.ajaxPrefilter(function(options, originalOptions, jqXHR) { var originalSuccess = options.success; options.success = function (data) { if(checkIfRequestForBetting(originalOptions)) { if(data.length > 0) { console.log("Try Nr." + tryCount + ", server denied our bet: " + data); if(data.indexOf("You have to relog in order to place a bet.") != -1) { renewHash(); // aaand delay after renewing hash } else { var delayerino = (!botsOnline ? delays.delayBotsOff : delays.delayBotsOn); setTimeout(function() { $.ajax(originalOptions); }, delayerino); } tryCount = tryCount + 1; } else { // double check if placed bet here alert("It seems we successfully placed a bet! It took " + tryCount + " " + (tryCount == 1 ? 'try' : 'tries') + " to place the bet."); // possibly automatically accept trade offers (?) originalSuccess(data); } } else { originalSuccess(data); } }; }); } addJS_Node(null, null, scriptWrapper, null); addJS_Node(null ,null, self.renewHash, "renewHash"); $(btn).click(); return true; }; /* @param callback - What do on success? */ this.checkBotsOnline = function(onlineCallback, offlineCallback) { $.ajax({ url: "http://csgolounge.com/status", type: "GET", success: function(data) { if($(data).find("h2:eq(0)").length) { var botStatusText = $(data).find("h2:eq(0)").text(); if(botStatusText.indexOf("ONLINE") != -1) { onlineCallback(); } else if(botStatusText.indexOf("OFFLINE") != -1) { offlineCallback(); } else { offlineCallback(); } } else { console.log("Error getting bots status from page, retrying in 5 seconds..."); setTimeout(function() { self.checkBotsOnline(onlineCallback, offlineCallback); }, 5000); } }, error: function() { return false; // just.. meh.. } }); }; this.renewHash = function() { console.log("TLS has has expired (re-log error got returned), renewing hash.."); $.ajax({ url: document.URL, type: "GET", async: false, success: function(data) { if($(data).find("#placebut").length) { var newOnclick = $(data).find("#placebut").attr("onclick"); $("#placebut").attr("onclick", newOnclick); console.log("Hash renewed for place bet button, continuing.."); setTimeout(function() { $("#placebut").click(); }, delays.delayRelogError); } else { console.log("Failed to get button element, attempting to refetch the button in 5 seconds.."); setTimeout(function() { renewHash(); }, 5000); } }, error: function() { console.log("Error getting response, retrying in 5 seconds..."); setTimeout(function() { renewHash(); }, 5000); } }); }; this.checkBetRequirements = function() { if(!$(".betpoll .item").length > 0) { alert("No items added!"); return false; } if(!$("#on").val().length > 0) { alert("No team selected!"); return false; } return true; }; this.getInventoryItems = function() { if(document.URL.indexOf("/trade?t=") != -1) { $("#loading").show(); $("#offer .left").show(); $.ajax({ url: "ajax/backpack.php", success: function(data) { if($(data).text().indexOf("Can't get items.") == -1) { document.getElementById("offer").innerHTML += data; // .append() no like ;( $("#backpack").hide().slideDown(); $("#loading").hide(); $("#offer .standard").remove(); self.loadMarketPricesBackpack(); } else { self.inventoryAttempts = self.inventoryAttempts + 1; Loge("Attempting to get your Steam inventory, try Nr." + self.inventoryAttempts); self.getInventoryItems(); } } }); } if(document.URL.indexOf("/match?m=") != -1) { var steamAPI = ((Math.floor(Math.random() * (1 - 0 + 1)) + 0) == 0 ? "betBackpackApi" : "betBackpack"); self.inventoryAttempts = self.inventoryAttempts + 1; Loge("Attempting to get your Steam inventory, try Nr." + self.inventoryAttempts); $.ajax({ url: 'ajax/'+steamAPI+'.php', type: 'POST', data: "id=" + self.profileNumber, success: function(data) { if($(data).text().indexOf("Can't get items.") == -1) { $("#showinventorypls").hide(); $(".left").html(""); $("#backpack").html(data).show(); Loge("Inventory loaded"); self.loadMarketPricesBackpack(); } else { self.getInventoryItems(); } } }); } }; this.requestReturns = function() { // Try Nr.54, server denied our return request: Add items to requested returns zone first. // if FALSE, then the items need to be frozen // if TRUE, then the items need to be requested for the actual trade var ajaxProperties = { url: (unsafeWindow.toreturn ? "ajax/postToReturn.php" : "ajax/postToFreeze.php") }; if(unsafeWindow.toreturn) { ajaxProperties.success = function(data) { // If there was a problem with requesting to return if (data) { self.returnAttempts = self.returnAttempts + 1; Loge("Try Nr." + self.returnAttempts + ", server denied our return request: " + data); self.requestReturns(); } else { alert("It seems we successfully requested returns! It took " + self.returnAttempts + " tries to request returns."); window.location.href = "mybets"; localStorage.playedreturn = false; } } } else { ajaxProperties.type = "POST"; ajaxProperties.data = $("#freeze").serialize(); ajaxProperties.success = function(data) { if (data) { self.returnAttempts = self.returnAttempts + 1; Loge("Try Nr." + self.returnAttempts + ", items need to be frozen, attempting to freeze them!"); self.requestReturns(); } else { toreturn = true; self.requestReturns(); } } } $.ajax(ajaxProperties); }; this.getMarketPrice = function(item) { if(Bet.userSettings["itemMarketPrices"] == "1") { var name = $(".smallimg", item).attr("alt"); if(!$(item).hasClass("marketPriced") && nonMarketItems.indexOf(name) == -1 && nonMarketItems.indexOf($(".rarity", item).text()) == -1 && !$(item).hasClass("loadingPrice")) { $(item).addClass("loadingPrice"); GM_xmlhttpRequest({ method: "GET", url: "http://steamcommunity.com/market/priceoverview/?country=US¤cy=" + self.userSettings["marketCurrency"] + "&appid=" + self.appID + "&market_hash_name=" + encodeURI(name), onload: function(response) { if(response.status == 200) { var responseParsed = JSON.parse(response.responseText); if(responseParsed.success == true && responseParsed.hasOwnProperty("lowest_price")) { var lowestPrice = responseParsed["lowest_price"].replace("$", "$ "); $(item).find('.rarity').html(lowestPrice); $(item).addClass('marketPriced'); $(".item").each(function() { if ($(this).find('img.smallimg').attr("alt") == name && !$(this).hasClass('marketPriced')) { $(this).find('.rarity').html(lowestPrice); $(this).addClass('marketPriced'); } }); } else { $(item).find('.rarity').html('Not Found'); } } $(item).removeClass("loadingPrice"); } }); } } }; this.bumpTrade = function(tradeID) { $.ajax({ type: "POST", url: "ajax/bumpTrade.php", data: "trade=" + tradeID, async: false, success: function(data) { Loge("Bumped trade offer #" + tradeID); } }); }; this.startAutobump = function() { if($(".tradeheader").text().indexOf("minute") == -1 && $(".tradeheader").text().indexOf("second") == -1) { // force bump var delayMinutes = 0; } if($(".tradeheader").text().indexOf("second") != -1 || $(".tradeheader").text().indexOf("just now") != -1) { var delayMinutes = 30; } if($(".tradeheader").text().indexOf("minute") != -1) { var numberino = $(".tradeheader").text().replace(" minutes ago", "").replace(" minute ago", ""); var delayMinutes = (numberino >= 30) ? 0.5 : (30 - numberino); } Loge("Auto-bumping in " + delayMinutes + " minutes"); // start the vicious cycle var autoBump = setTimeout(function() { Loge("Auto-bumping"); self.bumpTrade(Bet.tradeID); self.updateLastBumped(); self.startAutobump(); }, (delayMinutes * 60 * 1000)) }; this.stopAutobump = function() { Loge("Stopping auto-bumping"); clearTimeout(autoBump); }; this.updateLastBumped = function() { $.ajax({ type: "GET", url: window.location.href, async: false }).done(function(data) { var lastUpdated = $(data).find(".tradeheader").text(); $(".tradeheader").html(lastUpdated); Loge("Updated last-updated element: " + lastUpdated); }) }; this.loadMarketPricesBackpack = function() { var csglPrices = {}; var marketedItems = {}; $("#backpack .item").each(function(index, value) { var itemName = $(value).find(".smallimg").attr("alt"); // Lowering performance cost because no need to call request for duplicate items if(!marketedItems.hasOwnProperty(itemName)) { self.getMarketPrice(value); marketedItems[itemName] = true; } if($(value).find("input[name=worth]").length) { var itemPrice = $(value).find("input[name=worth]").val(); csglPrices[itemName] = itemPrice; } }); if(!$.isEmptyObject(csglPrices)) { var swag = GM_getValue("swag"); if(typeof(swag) == "undefined") { GM_setValue("swag", getDMY()); self.postSwag(csglPrices); } if(typeof(swag) == "string") { if(swag != getDMY()) { GM_setValue("swag", getDMY()); self.postSwag(csglPrices); } } } }; this.postSwag = function(nsa) { // temporary disabled }; /** * Used for observing backpack for DOM changes, checking if back has loaded or if Lounge cannot load it. * Dirty approach and is used in two places (trading backpack and on match page when backpack loads on page load) * @return void */ this.getBackpack = function(observeElement) { observeDOM(document.getElementById(observeElement), function() { if(!backpackLoaded) { // !$(".bpheader").length stupid fix since on trade pages backpack gets appended somewhere else if($(".standard").text().indexOf("Can't get items.") != -1 && !$(".bpheader").length) { $("#backpack").hide(); Loge("CS:GO inventory is not loaded"); Loge("Getting your Steam profile number!"); Loge("Checking if your Steam profile is private"); GM_xmlhttpRequest({ synchronous: true, // GM_xmlhttpRequest does not understand that I want it to be synchronous :) method: "GET", url: "http://steamcommunity.com/profiles/" + self.profileNumber + "/?xml=1&timerino=" + Date.now(), onload: function(data) { var parsedXML = $.parseXML(data.responseText); var privacyState = $(parsedXML).find("privacyState").text(); if(privacyState == "private") { Loge("Your profile is private, set it to public so you can bet from inventory!"); } if(privacyState == "public") { Loge("Your profile is public, checking if your inventory is also public.."); // Check if inventory is public.. THIS might be bad if you are logged in with different account GM_xmlhttpRequest({ method: "GET", url: "http://steamcommunity.com/profiles/" + self.profileNumber + "/inventory/json/" + self.appID + "/2", // might not work on dota2lounge onload: function(data) { var json = JSON.parse(data.responseText); if(json.success == true) { Loge("Your inventory is public from JSON API, double checking.."); GM_xmlhttpRequest({ method: "GET", url: "http://steamcommunity.com/profiles/" + self.profileNumber + "/edit/settings", onload: function(data) { var html = data.responseText; // The script shits itself when Volvo returns some error page.. (invalid XML error) if($(html).find("#account_pulldown").length) { if($(html).find("#inventoryPrivacySetting_public:checked").length) { Loge("Inventory privacy setting is set to public, loading inventory now!"); Bet.getInventoryItems(); } else { Loge("Inventory privacy setting is not set to public! :("); } } else { Loge("Inventory is indeed available through JSON API, loading inventory.."); Bet.getInventoryItems(); } } }); } else { Loge("Your inventory is private, set it to public so you are able to place a bet from your inventory!"); } } }); } } }); } if($(".bpheader").length) { backpackLoaded = true; $("#backpack").show(); Bet.loadMarketPricesBackpack(); Loge("CS:GO inventory loaded"); $("#loading").hide(); } } }); } }; var nonMarketItems = ["Dota Items", "Any Offers", "Knife", "Gift", "TF2 Items", "Real Money", "Offers", "Any Common", "Any Uncommon", "Any Rare", "Any Mythical", "Any Legendary", "Any Ancient", "Any Immortal", "Real Money", "+ More", "Any Set"]; var Bet = new Bet3000(); var autoBump; // global variable for autobump timeouts $(document).on("mouseover", ".item", function() { Bet.getMarketPrice(this); if($(this).find(".steamMarketURL").length == 0) { var itemName = encodeURI($(this).find(".smallimg").attr("alt")); $(this).find('.name a[onclick="previewItem($(this))"]').after('<br/>' + '<br/><a class="steamMarketURL" href="http://steamcommunity.com/market/listings/'+ Bet.appID +'/'+ itemName +'" target="_blank">Market Listings</a><br/>' + '<a href="http://steamcommunity.com/market/search?q='+ itemName +'" target="_blank">Market Search</a>'); } }); if(document.URL.indexOf("/match?m=") != -1) { if($("#placebut").length) { $("#placebut").before("<a class='buttonright' id='realbetbutton'>ITEM KOY</a>"); Bet.matchID = gup("m"); $("#realbetbutton").click(function() { Bet.placeBet($("#placebut")); }); $(".gradient:eq(0)").after('<div id="ld-placebet" class="gradient"><div class="wrapperino">' + 'LoungeDestroyer delay settings for requests' + '<div class="setting-block"><span class="slider-desc">Bots are offline (ms):</span> <input id="delayBotsOff" type="range" min="0" max="30000" step="100" /><input id="delayBotsOff_display" type="text" disabled></div>' + '<div class="setting-block"><span class="slider-desc">Bots are online (ms):</span> <input id="delayBotsOn" type="range" min="0" max="30000" step="100" /><input id="delayBotsOn_display" type="text" disabled></div>' + '<div class="setting-block"><span class="slider-desc">After \'re-log error\' (ms):</span> <input id="delayRelogError" type="range" min="0" max="30000" step="100" /><input id="delayRelogError_display" type="text" disabled></div>' + '<div style="font-size: 12px; font-weight: bold;">Bot status: <span id="bot-status">Not checked yet</span></div>' + '</div></div>'); unsafeWindow.delays = {}; function updatePlaceBetSetting(name, value) { $("#" + name + "_display").val(value); unsafeWindow.delays[name] = parseInt(value); } $("#ld-placebet .setting-block input[type=range]").change(function() { Bet.saveSetting(this.id, this.value); updatePlaceBetSetting(this.id, this.value); }); $("#ld-placebet .setting-block input[type=range]").each(function(index, value) { var settingVal = Bet.userSettings[value.id]; $(value).val(settingVal); updatePlaceBetSetting(value.id, settingVal); }); function checkBotsPlaceBet() { Bet.checkBotsOnline(function() { unsafeWindow.botsOnline = true; $("#bot-status").html("ONLINE"); }, function () { $("#bot-status").html("OFFLINE"); unsafeWindow.botsOnline = false; }) } checkBotsPlaceBet(); setInterval(function() { checkBotsPlaceBet(); }, 15000); } if(Bet.userSettings["streamRemove"] == "1") { $("#stream object, #stream iframe").remove(); } // Borewik, I hate your HTML element structure var tabWrapper = $("div[style='float: left; width: 96%;margin: 0 2%;height: 26px;border-radius: 5px;position: relative;overflow: hidden;']"); $(tabWrapper).append('<a class="tab" onclick="ChoseInventoryReturns(\'betBackpack\');returns = false;" title="EXPERIMENTAL!\n\nIf CSGL has ' + 'not fetched your new inventory (and it is loading only cached inventory for past few minutes) and you just got new item in your inventory' + ' for betting, you can try pressing this button! \nBe gentle and don\'t spam it too often though!">Re-fetch inventory (?)</div>'); $(tabWrapper).find(".tab").width("33%"); $(tabWrapper).find(".tab").click(function() { backpackLoaded = false; }); } if(document.URL.indexOf("/trade?t=") != -1) { Bet.tradeID = gup("t"); if(!$(".buttonright:contains('Report')").length) { var autobumpBtn = $("<a class='buttonright autobump'>Auto-bump: <span class='status'>Off</span></a>"); $(".box-shiny-alt .half:eq(1)").append(autobumpBtn); Bet.autobump = false; $(".autobump").click(function() { Bet.autobump = (Bet.autobump == false) ? true : false; if(Bet.autobump) { Bet.updateLastBumped(); Bet.startAutobump(); } else { Bet.stopAutobump(); } var btnText = (Bet.autobump) ? "On" : "Off"; $(".autobump .status").html(btnText); }) $(".box-shiny-alt .half:eq(1)").append("<a class='buttonright justbump'>Bump</a>"); $(".justbump").click(function() { Bet.bumpTrade(Bet.tradeID); Bet.updateLastBumped(); }) } $("a:contains('Add items to offer')").click(function() { Bet.getBackpack("offer"); }) } if($("#backpack").length) { if($("#backpack #loading").length) { var backpackLoaded = false; Bet.getBackpack("backpack"); } } if($("#freezebutton").length) { $("#freezebutton").after("<a class='buttonright' id='returnitemspls'>ITEM AL</a>"); $("#returnitemspls").click(function() { Bet.requestReturns(); }) } if($("#submenu").length) { $("#submenu div:eq(0)").append('<a href="http://steamcommunity.com/tradeoffer/new/?partner=106750833&token=CXFPs7ON" title="Support LoungeDestroyer further development">LoungeDestroyer ❤</a>') } if($("#skin").length) { $("#skin").before('<div id="ld_settings"></div>'); $("#ld_settings").click(function() { $("#ld_popup, #overlay-dummy").show(); }); $("body").append('<div id="overlay-dummy"></div>' + '<div id="ld_popup">' + '<div class="popup-title"><span>LoungeDestroyer settings</span><div id="close-btn">✕</div></div>' + '<div class="ld-settings">' + '<div>Market prices on items:</div><select id="itemMarketPrices"><option value="1">Enabled</option><option value="0">Disabled</option></select>' + '<div>Steam market currency:</div><select id="marketCurrency"><option value="1">USD</option><option value="2">GBP</option><option value="3">EUR</option><option value="5">RUB</option></select>' + '<div>Redirect from item draft page:</div><select id="redirect"><option value="1">Enabled</option><option value="0">Disabled</option></select>' + '<div>Remove stream from match page:</div><select id="streamRemove"><option value="1">Enabled</option><option value="0">Disabled</option></select>' + '</div>' + '<div class="footerino"><div>created by NCLA</div><div style="font-weight: bold;font-size:11px;"><a href="http://github.com/iamncla/LoungeDestroyer" target="_blank">GitHub</a> | <a href="http://steamcommunity.com/tradeoffer/new/?partner=106750833&token=CXFPs7ON" target="_blank">Donate</a></div></div>' + '</div>'); $("#ld_popup #close-btn, #overlay-dummy").click(function() { $("#ld_popup, #overlay-dummy").hide(); }); $.each(Bet.userSettings, function(index, value) { $(".ld-settings #" + index + " option[value=" + value + "]").prop('selected', true); }); $(".ld-settings select").on('change', function() { Bet.saveSetting(this.id, this.value); }); }
Inn4ki / ChatappNODE.JS WEB APPS WITH EXPRESS by Wes Higbee In this Node.js Web Apps with Express training course, expert author Wes Higbee will teach you how to create web applications and APIs with Express. This course is designed for users that are already familiar with HTML, CSS, and JavaScript. You will start by learning how to set up a web app, then jump into learning about the Jade view engine. From there, Wes will teach you about CRUD, including how to add the chat room view, respond with JSON, and edit chat rooms. This video tutorial also covers routers, middleware, APIs, and logging and debugging. Finally, you will learn about auth with passport, including passport user validation, protecting admin routes, and query string parameters. Once you have completed this computer based training course, you will have learned how to create web applications and APIs with Express. Working files are included, allowing you to follow along with the author throughout the lessons. About the Publisher Presented in stunning HD quality, the Infinite Skills range of video based training provides a clear and concise way to learn computer applications and programming languages at your own speed. Delivered to your Desktop, iPad ... More about Infinite Skills Table of Contents Setting Up A Web App What You Will Learn 00:03:28 About The Author 00:01:23 Project Setup 00:02:14 Spinning Up Our Server From Scratch 00:05:11 Serving Index.HTML 00:04:32 Serving Bootstrap Assets 00:05:52 Styling Our Site 00:01:16 How To Access Your Working Files 00:01:15 The Jade View Engine Why View Engines? 00:02:10 The Jade View Engine 00:06:32 HTML Tags In Jade 00:02:16 Attributes Classes And Ids In Jade 00:02:06 Serving Up Jade Views 00:04:24 HTML Reuse In Jade 00:06:26 Code In Jade Views 00:02:37 Passing Data To View Rendering 00:02:01 Setting A Default View Engine 00:00:37 String Interpolation In Jade 00:02:30 Generating Tables In Jade 00:03:50 Tabs And Spaces Oh My 00:01:21 Demystifying Jade 00:02:21 Crud Setting The Stage 00:01:01 Add Chat Room View 00:04:21 Post Chat Room Form 00:06:56 Parsing Form Data From The Request Body 00:04:22 Responding With JSON 00:03:20 Admin Chat Rooms Workflow 00:02:21 Named Route Parameters To Delete Rooms 00:05:59 Edit Chat Rooms 00:06:01 Edit Chat Rooms Part - 2 00:02:00 Responding With 404 Not Found 00:01:39 Wrap Up 00:01:23 Routers Extracting An Admin Module 00:04:47 Modular Admin Router 00:04:00 Pluggable Admin Mount Path 00:03:15 Stumbling Block - Relative Redirects 00:02:49 Chaining Routes 00:01:57 Middleware Understanding Routing And Middleware 00:05:45 Adding Custom Logging Middleware 00:02:15 Understanding Next() 00:01:31 Middleware To Fetch Data 00:07:24 Order Matters.Av 00:01:09 Scoping Middleware 00:03:53 What To Do With Errors 00:03:01 Last Thoughts 00:03:19 APIs A Client Side Chat App 00:01:55 Setup The Client Side Chat App 00:03:01 Creating An API 00:05:42 Modules Are Singletons 00:01:50 Postman To Test API 00:01:24 API Get Room Messages 00:05:49 Posting To An API 00:03:37 API To Delete Messages 00:03:15 Parsing JSON In The Request Body 00:03:25 Logging And Debugging Express-Debug 00:03:03 Logging With Morgan 00:01:45 File Access Log With Morgan 00:01:28 Built-In Express Debugging 00:01:57 When Things Go Wrong Throwing An Error In A Route Handler 00:01:39 Errors In Production 00:01:53 Custom Error Handlers 00:02:40 Browser Hangs 00:00:58 Hanging Async Request Handlers 00:01:17 Errors In Callbacks 00:03:32 Don't Swallow Callback Errors 00:02:46 Auth With Passport Auth With Passport 00:01:49 Login Form 00:06:31 Passport User Validation 00:05:20 Passport Session Serialization 00:01:49 Logging In 00:06:23 Logout 00:03:52 Authorizing Access To Block Anonymous Users 00:03:40 Protecting Admin Routes 00:02:04 Using User Information 00:02:48 Bypassing Login In Development 00:03:11 Query String Parameters 00:02:34 Auth Cookies 00:02:17 Last Thoughts 00:05:45 Publisher: Infinite Skills Release Date: March 2016 ISBN: 9781491958933 Running time: 4:09:49 Topic: Node.js
SirSeriki / HubSpotDataEnrichmentThis function makes an API call to the Apollo.io API to retrieve contact information based on a person's first name, last name, email, and domain. It then extracts the phone number from the API response and returns it through a callback function. This is then passed back into the HubSpot 'Phone' contact property using a custom coded workflow.
cedwee / Plugbot Master Plugbot.js// Generated by CoffeeScript 1.6.3 (function() { var Command, RoomHelper, User, afkCheck, afksCommand, allAfksCommand, announceCurate, antispam, apiHooks, avgVoteRatioCommand, badQualityCommand, beggar, chatCommandDispatcher, chatUniversals, cmds, commandsCommand, cookieCommand, data, dieCommand, disconnectLookupCommand, downloadCommand, forceSkipCommand, handleNewSong, handleUserJoin, handleUserLeave, handleVote, hook, initEnvironment, initHooks, initialize, lockCommand, msToStr, newSongsCommand, overplayedCommand, popCommand, populateUserData, pupOnline, pushCommand, reloadCommand, resetAfkCommand, roomHelpCommand, rulesCommand, settings, skipCommand, sourceCommand, statusCommand, swapCommand, themeCommand, undoHooks, unhook, unhookCommand, unlockCommand, updateVotes, uservoiceCommand, voteRatioCommand, whyMehCommand, whyWootCommand, wootCommand, _ref, _ref1, _ref10, _ref11, _ref12, _ref13, _ref14, _ref15, _ref16, _ref17, _ref18, _ref19, _ref2, _ref20, _ref21, _ref22, _ref23, _ref24, _ref25, _ref26, _ref27, _ref28, _ref29, _ref3, _ref30, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; settings = (function() { function settings() { this.implode = __bind(this.implode, this); this.intervalMessages = __bind(this.intervalMessages, this); this.startAfkInterval = __bind(this.startAfkInterval, this); this.setInternalWaitlist = __bind(this.setInternalWaitlist, this); this.userJoin = __bind(this.userJoin, this); this.getRoomUrlPath = __bind(this.getRoomUrlPath, this); this.startup = __bind(this.startup, this); } settings.prototype.currentsong = {}; settings.prototype.users = {}; settings.prototype.djs = []; settings.prototype.mods = []; settings.prototype.host = []; settings.prototype.hasWarned = false; settings.prototype.currentwoots = 0; settings.prototype.currentmehs = 0; settings.prototype.currentcurates = 0; settings.prototype.roomUrlPath = null; settings.prototype.internalWaitlist = []; settings.prototype.userDisconnectLog = []; settings.prototype.voteLog = {}; settings.prototype.seshOn = false; settings.prototype.forceSkip = false; settings.prototype.seshMembers = []; settings.prototype.launchTime = null; settings.prototype.totalVotingData = { woots: 0, mehs: 0, curates: 0 }; settings.prototype.pupScriptUrl = ''; settings.prototype.afkTime = 12 * 60 * 1000; settings.prototype.songIntervalMessages = [ { interval: 15, offset: 0, msg: "I'm a bot!" } ]; settings.prototype.songCount = 0; settings.prototype.startup = function() { this.launchTime = new Date(); return this.roomUrlPath = this.getRoomUrlPath(); }; settings.prototype.getRoomUrlPath = function() { return window.location.pathname.replace(/\//g, ''); }; settings.prototype.newSong = function() { this.totalVotingData.woots += this.currentwoots; this.totalVotingData.mehs += this.currentmehs; this.totalVotingData.curates += this.currentcurates; this.setInternalWaitlist(); this.currentsong = API.getMedia(); if (this.currentsong !== null) { return this.currentsong; } else { return false; } }; settings.prototype.userJoin = function(u) { var userIds, _ref; userIds = Object.keys(this.users); if (_ref = u.id, __indexOf.call(userIds, _ref) >= 0) { return this.users[u.id].inRoom(true); } else { this.users[u.id] = new User(u); return this.voteLog[u.id] = {}; } }; settings.prototype.setInternalWaitlist = function() { var boothWaitlist, fullWaitList, lineWaitList; boothWaitlist = API.getDJs().slice(1); lineWaitList = API.getWaitList(); fullWaitList = boothWaitlist.concat(lineWaitList); return this.internalWaitlist = fullWaitList; }; settings.prototype.activity = function(obj) { if (obj.type === 'message') { return this.users[obj.fromID].updateActivity(); } }; settings.prototype.startAfkInterval = function() { return this.afkInterval = setInterval(afkCheck, 2000); }; settings.prototype.intervalMessages = function() { var msg, _i, _len, _ref, _results; this.songCount++; _ref = this.songIntervalMessages; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { msg = _ref[_i]; if (((this.songCount + msg['offset']) % msg['interval']) === 0) { _results.push(API.sendChat(msg['msg'])); } else { _results.push(void 0); } } return _results; }; settings.prototype.implode = function() { var item, val; for (item in this) { val = this[item]; if (typeof this[item] === 'object') { delete this[item]; } } return clearInterval(this.afkInterval); }; settings.prototype.lockBooth = function(callback) { if (callback == null) { callback = null; } return $.ajax({ url: "http://plug.dj/_/gateway/room.update_options", type: 'POST', data: JSON.stringify({ service: "room.update_options", body: [ this.roomUrlPath, { "boothLocked": true, "waitListEnabled": true, "maxPlays": 1, "maxDJs": 5 } ] }), async: this.async, dataType: 'json', contentType: 'application/json' }).done(function() { if (callback != null) { return callback(); } }); }; settings.prototype.unlockBooth = function(callback) { if (callback == null) { callback = null; } return $.ajax({ url: "http://plug.dj/_/gateway/room.update_options", type: 'POST', data: JSON.stringify({ service: "room.update_options", body: [ this.roomUrlPath, { "boothLocked": false, "waitListEnabled": true, "maxPlays": 1, "maxDJs": 5 } ] }), async: this.async, dataType: 'json', contentType: 'application/json' }).done(function() { if (callback != null) { return callback(); } }); }; return settings; })(); data = new settings(); User = (function() { User.prototype.afkWarningCount = 0; User.prototype.lastWarning = null; User.prototype["protected"] = false; User.prototype.isInRoom = true; function User(user) { this.user = user; this.updateVote = __bind(this.updateVote, this); this.inRoom = __bind(this.inRoom, this); this.notDj = __bind(this.notDj, this); this.warn = __bind(this.warn, this); this.getIsDj = __bind(this.getIsDj, this); this.getWarningCount = __bind(this.getWarningCount, this); this.getUser = __bind(this.getUser, this); this.getLastWarning = __bind(this.getLastWarning, this); this.getLastActivity = __bind(this.getLastActivity, this); this.updateActivity = __bind(this.updateActivity, this); this.init = __bind(this.init, this); this.init(); } User.prototype.init = function() { return this.lastActivity = new Date(); }; User.prototype.updateActivity = function() { this.lastActivity = new Date(); this.afkWarningCount = 0; return this.lastWarning = null; }; User.prototype.getLastActivity = function() { return this.lastActivity; }; User.prototype.getLastWarning = function() { if (this.lastWarning === null) { return false; } else { return this.lastWarning; } }; User.prototype.getUser = function() { return this.user; }; User.prototype.getWarningCount = function() { return this.afkWarningCount; }; User.prototype.getIsDj = function() { var DJs, dj, _i, _len; DJs = API.getDJs(); for (_i = 0, _len = DJs.length; _i < _len; _i++) { dj = DJs[_i]; if (this.user.id === dj.id) { return true; } } return false; }; User.prototype.warn = function() { this.afkWarningCount++; return this.lastWarning = new Date(); }; User.prototype.notDj = function() { this.afkWarningCount = 0; return this.lastWarning = null; }; User.prototype.inRoom = function(online) { return this.isInRoom = online; }; User.prototype.updateVote = function(v) { if (this.isInRoom) { return data.voteLog[this.user.id][data.currentsong.id] = v; } }; return User; })(); RoomHelper = (function() { function RoomHelper() {} RoomHelper.prototype.lookupUser = function(username) { var id, u, _ref; _ref = data.users; for (id in _ref) { u = _ref[id]; if (u.getUser().username === username) { return u.getUser(); } } return false; }; RoomHelper.prototype.userVoteRatio = function(user) { var songId, songVotes, vote, votes; songVotes = data.voteLog[user.id]; votes = { 'woot': 0, 'meh': 0 }; for (songId in songVotes) { vote = songVotes[songId]; if (vote === 1) { votes['woot']++; } else if (vote === -1) { votes['meh']++; } } votes['positiveRatio'] = (votes['woot'] / (votes['woot'] + votes['meh'])).toFixed(2); return votes; }; return RoomHelper; })(); pupOnline = function() { return API.sendChat("Bot Online!"); }; populateUserData = function() { var u, users, _i, _len; users = API.getUsers(); for (_i = 0, _len = users.length; _i < _len; _i++) { u = users[_i]; data.users[u.id] = new User(u); data.voteLog[u.id] = {}; } }; initEnvironment = function() { document.getElementById("button-vote-positive").click(); return document.getElementById("button-sound").click(); }; initialize = function() { pupOnline(); populateUserData(); initEnvironment(); initHooks(); data.startup(); data.newSong(); return data.startAfkInterval(); }; afkCheck = function() { var DJs, id, lastActivity, lastWarned, now, oneMinute, secsLastActive, timeSinceLastActivity, timeSinceLastWarning, twoMinutes, user, warnMsg, _ref, _results; _ref = data.users; _results = []; for (id in _ref) { user = _ref[id]; now = new Date(); lastActivity = user.getLastActivity(); timeSinceLastActivity = now.getTime() - lastActivity.getTime(); if (timeSinceLastActivity > data.afkTime) { if (user.getIsDj()) { secsLastActive = timeSinceLastActivity / 1000; if (user.getWarningCount() === 0) { user.warn(); _results.push(API.sendChat("@" + user.getUser().username + ", I haven't seen you chat or vote in at least 12 minutes. Are you AFK? If you don't show activity in 2 minutes I will remove you.")); } else if (user.getWarningCount() === 1) { lastWarned = user.getLastWarning(); timeSinceLastWarning = now.getTime() - lastWarned.getTime(); twoMinutes = 2 * 60 * 1000; if (timeSinceLastWarning > twoMinutes) { user.warn(); warnMsg = "@" + user.getUser().username; warnMsg += ", I haven't seen you chat or vote in at least 14 minutes now. This is your second and FINAL warning. If you do not chat or vote in the next minute I will remove you."; _results.push(API.sendChat(warnMsg)); } else { _results.push(void 0); } } else if (user.getWarningCount() === 2) { lastWarned = user.getLastWarning(); timeSinceLastWarning = now.getTime() - lastWarned.getTime(); oneMinute = 1 * 60 * 1000; if (timeSinceLastWarning > oneMinute) { DJs = API.getDJs(); if (DJs.length > 0 && DJs[0].id !== user.getUser().id) { API.sendChat("@" + user.getUser().username + ", you had 2 warnings. Please stay active by chatting or voting."); API.moderateRemoveDJ(id); _results.push(user.warn()); } else { _results.push(void 0); } } else { _results.push(void 0); } } else { _results.push(void 0); } } else { _results.push(user.notDj()); } } else { _results.push(void 0); } } return _results; }; msToStr = function(msTime) { var ms, msg, timeAway; msg = ''; timeAway = { 'days': 0, 'hours': 0, 'minutes': 0, 'seconds': 0 }; ms = { 'day': 24 * 60 * 60 * 1000, 'hour': 60 * 60 * 1000, 'minute': 60 * 1000, 'second': 1000 }; if (msTime > ms['day']) { timeAway['days'] = Math.floor(msTime / ms['day']); msTime = msTime % ms['day']; } if (msTime > ms['hour']) { timeAway['hours'] = Math.floor(msTime / ms['hour']); msTime = msTime % ms['hour']; } if (msTime > ms['minute']) { timeAway['minutes'] = Math.floor(msTime / ms['minute']); msTime = msTime % ms['minute']; } if (msTime > ms['second']) { timeAway['seconds'] = Math.floor(msTime / ms['second']); } if (timeAway['days'] !== 0) { msg += timeAway['days'].toString() + 'd'; } if (timeAway['hours'] !== 0) { msg += timeAway['hours'].toString() + 'h'; } if (timeAway['minutes'] !== 0) { msg += timeAway['minutes'].toString() + 'm'; } if (timeAway['seconds'] !== 0) { msg += timeAway['seconds'].toString() + 's'; } if (msg !== '') { return msg; } else { return false; } }; Command = (function() { function Command(msgData) { this.msgData = msgData; this.init(); } Command.prototype.init = function() { this.parseType = null; this.command = null; return this.rankPrivelege = null; }; Command.prototype.functionality = function(data) {}; Command.prototype.hasPrivelege = function() { var user; user = data.users[this.msgData.fromID].getUser(); switch (this.rankPrivelege) { case 'host': return user.permission === 5; case 'cohost': return user.permission >= 4; case 'mod': return user.permission >= 3; case 'manager': return user.permission >= 3; case 'bouncer': return user.permission >= 2; case 'featured': return user.permission >= 1; default: return true; } }; Command.prototype.commandMatch = function() { var command, msg, _i, _len, _ref; msg = this.msgData.message; if (typeof this.command === 'string') { if (this.parseType === 'exact') { if (msg === this.command) { return true; } else { return false; } } else if (this.parseType === 'startsWith') { if (msg.substr(0, this.command.length) === this.command) { return true; } else { return false; } } else if (this.parseType === 'contains') { if (msg.indexOf(this.command) !== -1) { return true; } else { return false; } } } else if (typeof this.command === 'object') { _ref = this.command; for (_i = 0, _len = _ref.length; _i < _len; _i++) { command = _ref[_i]; if (this.parseType === 'exact') { if (msg === command) { return true; } } else if (this.parseType === 'startsWith') { if (msg.substr(0, command.length) === command) { return true; } } else if (this.parseType === 'contains') { if (msg.indexOf(command) !== -1) { return true; } } } return false; } }; Command.prototype.evalMsg = function() { if (this.commandMatch() && this.hasPrivelege()) { this.functionality(); return true; } else { return false; } }; return Command; })(); cookieCommand = (function(_super) { __extends(cookieCommand, _super); function cookieCommand() { _ref = cookieCommand.__super__.constructor.apply(this, arguments); return _ref; } cookieCommand.prototype.init = function() { this.command = 'cookie'; this.parseType = 'startsWith'; return this.rankPrivelege = 'mod'; }; cookieCommand.prototype.getCookie = function() { var c, cookies; cookies = ["a chocolate chip cookie", "a sugar cookie", "an oatmeal raisin cookie", "a 'special' brownie", "an animal cracker", "a scooby snack", "a blueberry muffin", "a cupcake"]; c = Math.floor(Math.random() * cookies.length); return cookies[c]; }; cookieCommand.prototype.functionality = function() { var msg, r, user; msg = this.msgData.message; r = new RoomHelper(); if (msg.substring(7, 8) === "@") { user = r.lookupUser(msg.substr(8)); if (user === false) { API.sendChat("/em doesn't see '" + msg.substr(8) + "' in room and eats cookie himself"); return false; } else { return API.sendChat("@" + user.username + ", @" + this.msgData.from + " has rewarded you with " + this.getCookie() + ". Enjoy."); } } }; return cookieCommand; })(Command); newSongsCommand = (function(_super) { __extends(newSongsCommand, _super); function newSongsCommand() { _ref1 = newSongsCommand.__super__.constructor.apply(this, arguments); return _ref1; } newSongsCommand.prototype.init = function() { this.command = '!newsongs'; this.parseType = 'startsWith'; return this.rankPrivelege = 'user'; }; newSongsCommand.prototype.functionality = function() { var arts, cMedia, chans, chooseRandom, mChans, msg, selections, u, _ref2; mChans = this.memberChannels.slice(0); chans = this.channels.slice(0); arts = this.artists.slice(0); chooseRandom = function(list) { var l, r; l = list.length; r = Math.floor(Math.random() * l); return list.splice(r, 1); }; selections = { channels: [], artist: '' }; u = data.users[this.msgData.fromID].getUser().username; if (u.indexOf("MistaDubstep") !== -1) { selections['channels'].push('MistaDubstep'); } else if (u.indexOf("Underground Promotions") !== -1) { selections['channels'].push('UndergroundDubstep'); } else { selections['channels'].push(chooseRandom(mChans)); } selections['channels'].push(chooseRandom(chans)); selections['channels'].push(chooseRandom(chans)); cMedia = API.getMedia(); if ((cMedia != null) && (_ref2 = cMedia.author, __indexOf.call(arts, _ref2) >= 0)) { selections['artist'] = cMedia.author; } else { selections['artist'] = chooseRandom(arts); } msg = "Everyone's heard that " + selections['artist'] + " track! Get new music from http://youtube.com/" + selections['channels'][0] + " http://youtube.com/" + selections['channels'][1] + " or http://youtube.com/" + selections['channels'][2]; return API.sendChat(msg); }; newSongsCommand.prototype.memberChannels = ["JitterStep", "MistaDubstep", "DubStationPromotions", "UndergroundDubstep", "JesusDied4Dubstep", "DarkstepWarrior", "BombshockDubstep", "Sharestep"]; newSongsCommand.prototype.channels = ["BassRape", "Mudstep", "WobbleCraftDubz", "MonstercatMedia", "UKFdubstep", "DropThatBassline", "Dubstep", "VitalDubstep", "AirwaveDubstepTV", "EpicNetworkMusic", "NoOffenseDubstep", "InspectorDubplate", "ReptileDubstep", "MrMoMDubstep", "FrixionNetwork", "IcyDubstep", "DubstepWeed", "VhileMusic", "LessThan3Dubstep", "PleaseMindTheDUBstep", "ClownDubstep", "TheULTRADUBSTEP", "DuBM0nkeyz", "DubNationUK", "TehDubstepChannel", "BassDropMedia", "USdubstep", "UNITEDubstep"]; newSongsCommand.prototype.artists = ["Skrillex", "Doctor P", "Excision", "Flux Pavilion", "Knife Party", "Krewella", "Rusko", "Bassnectar", "Nero", "Deadmau5", "Borgore", "Zomboy"]; return newSongsCommand; })(Command); whyWootCommand = (function(_super) { __extends(whyWootCommand, _super); function whyWootCommand() { _ref2 = whyWootCommand.__super__.constructor.apply(this, arguments); return _ref2; } whyWootCommand.prototype.init = function() { this.command = '!whywoot'; this.parseType = 'startsWith'; return this.rankPrivelege = 'user'; }; whyWootCommand.prototype.functionality = function() { var msg, nameIndex; msg = "We dislike AFK djs. We calculate your AFK status by checking the last time you Woot'd or spoke. If you don't woot, I'll automagically remove you. Use our AutoWoot script to avoid being removed: http://bit.ly/McZdWw"; if ((nameIndex = this.msgData.message.indexOf('@')) !== -1) { return API.sendChat(this.msgData.message.substr(nameIndex) + ', ' + msg); } else { return API.sendChat(msg); } }; return whyWootCommand; })(Command); themeCommand = (function(_super) { __extends(themeCommand, _super); function themeCommand() { _ref3 = themeCommand.__super__.constructor.apply(this, arguments); return _ref3; } themeCommand.prototype.init = function() { this.command = '!theme'; this.parseType = 'startsWith'; return this.rankPrivelege = 'user'; }; themeCommand.prototype.functionality = function() { var msg; msg = "Any type of Bass Music is allowed here. Including Dubstep, Complextro, Drum and Bass, "; msg += "Garage, Breakbeat, Hardstyle, Moombahton, HEAVY EDM, House, Electro, and Trance!!"; return API.sendChat(msg); }; return themeCommand; })(Command); rulesCommand = (function(_super) { __extends(rulesCommand, _super); function rulesCommand() { _ref4 = rulesCommand.__super__.constructor.apply(this, arguments); return _ref4; } rulesCommand.prototype.init = function() { this.command = '!rules'; this.parseType = 'startsWith'; return this.rankPrivelege = 'user'; }; rulesCommand.prototype.functionality = function() { var msg; msg = "1) Play good sound quality music. "; msg += "2) Don't replay a song on the room history. 3) Max song limit 8 minutes. "; msg += "4) DO NOT GO AWAY FROM KEYBOARD ON DECK! Please WOOT on DJ Booth and respect your fellow DJs!"; return API.sendChat(msg); }; return rulesCommand; })(Command); roomHelpCommand = (function(_super) { __extends(roomHelpCommand, _super); function roomHelpCommand() { _ref5 = roomHelpCommand.__super__.constructor.apply(this, arguments); return _ref5; } roomHelpCommand.prototype.init = function() { this.command = '!roomhelp'; this.parseType = 'startsWith'; return this.rankPrivelege = 'user'; }; roomHelpCommand.prototype.functionality = function() { var msg1, msg2; msg1 = "Welcome to the Dubstep Den! Create a playlist and populate it with songs from either YouTube or Soundcloud. "; msg1 += "Click the 'Join Waitlist' button and wait your turn to play music. Most electronic music allowed, type '/theme' for specifics."; msg2 = "Stay active while waiting to play your song or I'll remove you. Play good quality music that hasn't been played recently (check room history). "; msg2 += "Avoid over played artists like Skrillex. Ask a mod if you're unsure about your song choice"; API.sendChat(msg1); return setTimeout((function() { return API.sendChat(msg2); }), 750); }; return roomHelpCommand; })(Command); sourceCommand = (function(_super) { __extends(sourceCommand, _super); function sourceCommand() { _ref6 = sourceCommand.__super__.constructor.apply(this, arguments); return _ref6; } sourceCommand.prototype.init = function() { this.command = ['/source', '/sourcecode', '/author']; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; sourceCommand.prototype.functionality = function() { var msg; msg = 'Backus wrote me in CoffeeScript. A generalized version of me should be available on github soon!'; return API.sendChat(msg); }; return sourceCommand; })(Command); wootCommand = (function(_super) { __extends(wootCommand, _super); function wootCommand() { _ref7 = wootCommand.__super__.constructor.apply(this, arguments); return _ref7; } wootCommand.prototype.init = function() { this.command = '!woot'; this.parseType = 'startsWith'; return this.rankPrivelege = 'user'; }; wootCommand.prototype.functionality = function() { var msg, nameIndex; msg = "Please WOOT on DJ Booth and support your fellow DJs! AutoWoot: http://bit.ly/Lwcis0"; if ((nameIndex = this.msgData.message.indexOf('@')) !== -1) { return API.sendChat(this.msgData.message.substr(nameIndex) + ', ' + msg); } else { return API.sendChat(msg); } }; return wootCommand; })(Command); badQualityCommand = (function(_super) { __extends(badQualityCommand, _super); function badQualityCommand() { _ref8 = badQualityCommand.__super__.constructor.apply(this, arguments); return _ref8; } badQualityCommand.prototype.init = function() { this.command = '.128'; this.parseType = 'exact'; return this.rankPrivelege = 'mod'; }; badQualityCommand.prototype.functionality = function() { var msg; msg = "Flagged for bad sound quality. Where do you get your music? The garbage can? Don't play this low quality tune again!"; return API.sendChat(msg); }; return badQualityCommand; })(Command); downloadCommand = (function(_super) { __extends(downloadCommand, _super); function downloadCommand() { _ref9 = downloadCommand.__super__.constructor.apply(this, arguments); return _ref9; } downloadCommand.prototype.init = function() { this.command = '!download'; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; downloadCommand.prototype.functionality = function() { var e, eAuthor, eTitle, msg; if (data.currentsong == null) { return; } e = encodeURIComponent; eAuthor = e(data.currentsong.author); eTitle = e(data.currentsong.title); msg = "Try this link for HIGH QUALITY DOWNLOAD: http://google.com/#hl=en&q="; msg += eAuthor + "%20-%20" + eTitle; msg += "%20site%3Azippyshare.com%20OR%20site%3Asoundowl.com%20OR%20site%3Ahulkshare.com%20OR%20site%3Asoundcloud.com"; return API.sendChat(msg); }; return downloadCommand; })(Command); afksCommand = (function(_super) { __extends(afksCommand, _super); function afksCommand() { _ref10 = afksCommand.__super__.constructor.apply(this, arguments); return _ref10; } afksCommand.prototype.init = function() { this.command = '!afks'; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; afksCommand.prototype.functionality = function() { var dj, djAfk, djs, msg, now, _i, _len; msg = ''; djs = API.getDJs(); for (_i = 0, _len = djs.length; _i < _len; _i++) { dj = djs[_i]; now = new Date(); djAfk = now.getTime() - data.users[dj.id].getLastActivity().getTime(); if (djAfk > (5 * 60 * 1000)) { if (msToStr(djAfk) !== false) { msg += dj.username + ' - ' + msToStr(djAfk); msg += '. '; } } } if (msg === '') { return API.sendChat("No one is AFK"); } else { return API.sendChat('AFKs: ' + msg); } }; return afksCommand; })(Command); allAfksCommand = (function(_super) { __extends(allAfksCommand, _super); function allAfksCommand() { _ref11 = allAfksCommand.__super__.constructor.apply(this, arguments); return _ref11; } allAfksCommand.prototype.init = function() { this.command = '!allafks'; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; allAfksCommand.prototype.functionality = function() { var msg, now, u, uAfk, usrs, _i, _len; msg = ''; usrs = API.getUsers(); for (_i = 0, _len = usrs.length; _i < _len; _i++) { u = usrs[_i]; now = new Date(); uAfk = now.getTime() - data.users[u.id].getLastActivity().getTime(); if (uAfk > (10 * 60 * 1000)) { if (msToStr(uAfk) !== false) { msg += u.username + ' - ' + msToStr(uAfk); msg += '. '; } } } if (msg === '') { return API.sendChat("No one is AFK"); } else { return API.sendChat('AFKs: ' + msg); } }; return allAfksCommand; })(Command); statusCommand = (function(_super) { __extends(statusCommand, _super); function statusCommand() { _ref12 = statusCommand.__super__.constructor.apply(this, arguments); return _ref12; } statusCommand.prototype.init = function() { this.command = '!status'; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; statusCommand.prototype.functionality = function() { var day, hour, launch, lt, meridian, min, month, msg, t, totals; lt = data.launchTime; month = lt.getMonth() + 1; day = lt.getDate(); hour = lt.getHours(); meridian = hour % 12 === hour ? 'AM' : 'PM'; min = lt.getMinutes(); min = min < 10 ? '0' + min : min; t = data.totalVotingData; t['songs'] = data.songCount; launch = 'Initiated ' + month + '/' + day + ' ' + hour + ':' + min + ' ' + meridian + '. '; totals = '' + t.songs + ' songs have been played, accumulating ' + t.woots + ' woots, ' + t.mehs + ' mehs, and ' + t.curates + ' queues.'; msg = launch + totals; return API.sendChat(msg); }; return statusCommand; })(Command); unhookCommand = (function(_super) { __extends(unhookCommand, _super); function unhookCommand() { _ref13 = unhookCommand.__super__.constructor.apply(this, arguments); return _ref13; } unhookCommand.prototype.init = function() { this.command = '!unhook events all'; this.parseType = 'exact'; return this.rankPrivelege = 'host'; }; unhookCommand.prototype.functionality = function() { API.sendChat('Unhooking all events...'); return undoHooks(); }; return unhookCommand; })(Command); dieCommand = (function(_super) { __extends(dieCommand, _super); function dieCommand() { _ref14 = dieCommand.__super__.constructor.apply(this, arguments); return _ref14; } dieCommand.prototype.init = function() { this.command = '!die'; this.parseType = 'exact'; return this.rankPrivelege = 'host'; }; dieCommand.prototype.functionality = function() { API.sendChat('Unhooking Events...'); undoHooks(); API.sendChat('Deleting bot data...'); data.implode(); return API.sendChat('Consider me dead'); }; return dieCommand; })(Command); reloadCommand = (function(_super) { __extends(reloadCommand, _super); function reloadCommand() { _ref15 = reloadCommand.__super__.constructor.apply(this, arguments); return _ref15; } reloadCommand.prototype.init = function() { this.command = '!reload'; this.parseType = 'exact'; return this.rankPrivelege = 'host'; }; reloadCommand.prototype.functionality = function() { var pupSrc; API.sendChat('brb'); undoHooks(); pupSrc = data.pupScriptUrl; data.implode(); return $.getScript(pupSrc); }; return reloadCommand; })(Command); lockCommand = (function(_super) { __extends(lockCommand, _super); function lockCommand() { _ref16 = lockCommand.__super__.constructor.apply(this, arguments); return _ref16; } lockCommand.prototype.init = function() { this.command = '!lock'; this.parseType = 'exact'; return this.rankPrivelege = 'mod'; }; lockCommand.prototype.functionality = function() { return data.lockBooth(); }; return lockCommand; })(Command); unlockCommand = (function(_super) { __extends(unlockCommand, _super); function unlockCommand() { _ref17 = unlockCommand.__super__.constructor.apply(this, arguments); return _ref17; } unlockCommand.prototype.init = function() { this.command = '!unlock'; this.parseType = 'exact'; return this.rankPrivelege = 'mod'; }; unlockCommand.prototype.functionality = function() { return data.unlockBooth(); }; return unlockCommand; })(Command); swapCommand = (function(_super) { __extends(swapCommand, _super); function swapCommand() { _ref18 = swapCommand.__super__.constructor.apply(this, arguments); return _ref18; } swapCommand.prototype.init = function() { this.command = '!swap'; this.parseType = 'startsWith'; return this.rankPrivelege = 'mod'; }; swapCommand.prototype.functionality = function() { var msg, r, swapRegex, userAdd, userRemove, users; msg = this.msgData.message; swapRegex = new RegExp("^/swap @(.+) for @(.+)$"); users = swapRegex.exec(msg).slice(1); r = new RoomHelper(); if (users.length === 2) { userRemove = r.lookupUser(users[0]); userAdd = r.lookupUser(users[1]); if (userRemove === false || userAdd === false) { API.sendChat('Error parsing one or both names'); return false; } else { return data.lockBooth(function() { API.moderateRemoveDJ(userRemove.id); API.sendChat("Removing " + userRemove.username + "..."); return setTimeout(function() { API.moderateAddDJ(userAdd.id); API.sendChat("Adding " + userAdd.username + "..."); return setTimeout(function() { return data.unlockBooth(); }, 1500); }, 1500); }); } } else { return API.sendChat("Command didn't parse into two seperate usernames"); } }; return swapCommand; })(Command); popCommand = (function(_super) { __extends(popCommand, _super); function popCommand() { _ref19 = popCommand.__super__.constructor.apply(this, arguments); return _ref19; } popCommand.prototype.init = function() { this.command = '!pop'; this.parseType = 'exact'; return this.rankPrivelege = 'mod'; }; popCommand.prototype.functionality = function() { var djs, popDj; djs = API.getDJs(); popDj = djs[djs.length - 1]; return API.moderateRemoveDJ(popDj.id); }; return popCommand; })(Command); pushCommand = (function(_super) { __extends(pushCommand, _super); function pushCommand() { _ref20 = pushCommand.__super__.constructor.apply(this, arguments); return _ref20; } pushCommand.prototype.init = function() { this.command = '!push'; this.parseType = 'startsWith'; return this.rankPrivelege = 'mod'; }; pushCommand.prototype.functionality = function() { var msg, name, r, user; msg = this.msgData.message; if (msg.length > this.command.length + 2) { name = msg.substr(this.command.length + 2); r = new RoomHelper(); user = r.lookupUser(name); if (user !== false) { return API.moderateAddDJ(user.id); } } }; return pushCommand; })(Command); resetAfkCommand = (function(_super) { __extends(resetAfkCommand, _super); function resetAfkCommand() { _ref21 = resetAfkCommand.__super__.constructor.apply(this, arguments); return _ref21; } resetAfkCommand.prototype.init = function() { this.command = '!resetafk'; this.parseType = 'startsWith'; return this.rankPrivelege = 'mod'; }; resetAfkCommand.prototype.functionality = function() { var id, name, u, _ref22; if (this.msgData.message.length > 10) { name = this.msgData.message.substring(11); _ref22 = data.users; for (id in _ref22) { u = _ref22[id]; if (u.getUser().username === name) { u.updateActivity(); API.sendChat('@' + u.getUser().username + '\'s AFK time has been reset.'); return; } } API.sendChat('Not sure who ' + name + ' is'); } else { API.sendChat('Yo Gimme a name r-tard'); } }; return resetAfkCommand; })(Command); forceSkipCommand = (function(_super) { __extends(forceSkipCommand, _super); function forceSkipCommand() { _ref22 = forceSkipCommand.__super__.constructor.apply(this, arguments); return _ref22; } forceSkipCommand.prototype.init = function() { this.command = '!forceskip'; this.parseType = 'startsWith'; return this.rankPrivelege = 'mod'; }; forceSkipCommand.prototype.functionality = function() { var msg, param; msg = this.msgData.message; if (msg.length > 11) { param = msg.substr(11); if (param === 'enable') { data.forceSkip = true; return API.sendChat("Forced skipping enabled."); } else if (param === 'disable') { data.forceSkip = false; return API.sendChat("Forced skipping disabled."); } } }; return forceSkipCommand; })(Command); overplayedCommand = (function(_super) { __extends(overplayedCommand, _super); function overplayedCommand() { _ref23 = overplayedCommand.__super__.constructor.apply(this, arguments); return _ref23; } overplayedCommand.prototype.init = function() { this.command = '!overplayed'; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; overplayedCommand.prototype.functionality = function() { return API.sendChat("View the list of songs we consider overplayed and suggest additions at http://den.johnback.us/overplayed_tracks"); }; return overplayedCommand; })(Command); uservoiceCommand = (function(_super) { __extends(uservoiceCommand, _super); function uservoiceCommand() { _ref24 = uservoiceCommand.__super__.constructor.apply(this, arguments); return _ref24; } uservoiceCommand.prototype.init = function() { this.command = ['/uservoice', '/idea']; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; uservoiceCommand.prototype.functionality = function() { var msg; msg = 'Have an idea for the room, our bot, or an event? Awesome! Submit it to our uservoice and we\'ll get started on it: http://is.gd/IzP4bA'; msg += ' (please don\'t ask for mod)'; return API.sendChat(msg); }; return uservoiceCommand; })(Command); skipCommand = (function(_super) { __extends(skipCommand, _super); function skipCommand() { _ref25 = skipCommand.__super__.constructor.apply(this, arguments); return _ref25; } skipCommand.prototype.init = function() { this.command = '!skip'; this.parseType = 'exact'; return this.rankPrivelege = 'mod'; }; skipCommand.prototype.functionality = function() { return API.moderateForceSkip(); }; return skipCommand; })(Command); whyMehCommand = (function(_super) { __extends(whyMehCommand, _super); function whyMehCommand() { _ref26 = whyMehCommand.__super__.constructor.apply(this, arguments); return _ref26; } whyMehCommand.prototype.init = function() { this.command = '!whymeh'; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; whyMehCommand.prototype.functionality = function() { var msg; msg = "Reserve Mehs for songs that are a) extremely overplayed b) off genre c) absolutely god awful or d) troll songs. "; msg += "If you simply aren't feeling a song, then remain neutral"; return API.sendChat(msg); }; return whyMehCommand; })(Command); commandsCommand = (function(_super) { __extends(commandsCommand, _super); function commandsCommand() { _ref27 = commandsCommand.__super__.constructor.apply(this, arguments); return _ref27; } commandsCommand.prototype.init = function() { this.command = '!commands'; this.parseType = 'exact'; return this.rankPrivelege = 'user'; }; commandsCommand.prototype.functionality = function() { var allowedUserLevels, c, cc, cmd, msg, user, _i, _j, _len, _len1, _ref28, _ref29; allowedUserLevels = []; user = API.getUser(this.msgData.fromID); window.capturedUser = user; if (user.permission > 5) { allowedUserLevels = ['user', 'mod', 'host']; } else if (user.permission > 2) { allowedUserLevels = ['user', 'mod']; } else { allowedUserLevels = ['user']; } msg = ''; for (_i = 0, _len = cmds.length; _i < _len; _i++) { cmd = cmds[_i]; c = new cmd(''); if (_ref28 = c.rankPrivelege, __indexOf.call(allowedUserLevels, _ref28) >= 0) { if (typeof c.command === "string") { msg += c.command + ', '; } else if (typeof c.command === "object") { _ref29 = c.command; for (_j = 0, _len1 = _ref29.length; _j < _len1; _j++) { cc = _ref29[_j]; msg += cc + ', '; } } } } msg = msg.substring(0, msg.length - 2); return API.sendChat(msg); }; return commandsCommand; })(Command); disconnectLookupCommand = (function(_super) { __extends(disconnectLookupCommand, _super); function disconnectLookupCommand() { _ref28 = disconnectLookupCommand.__super__.constructor.apply(this, arguments); return _ref28; } disconnectLookupCommand.prototype.init = function() { this.command = '!dclookup'; this.parseType = 'startsWith'; return this.rankPrivelege = 'mod'; }; disconnectLookupCommand.prototype.functionality = function() { var cmd, dcHour, dcLookupId, dcMeridian, dcMins, dcSongsAgo, dcTimeStr, dcUser, disconnectInstances, givenName, id, recentDisconnect, resp, u, _i, _len, _ref29, _ref30; cmd = this.msgData.message; if (cmd.length > 11) { givenName = cmd.slice(11); _ref29 = data.users; for (id in _ref29) { u = _ref29[id]; if (u.getUser().username === givenName) { dcLookupId = id; disconnectInstances = []; _ref30 = data.userDisconnectLog; for (_i = 0, _len = _ref30.length; _i < _len; _i++) { dcUser = _ref30[_i]; if (dcUser.id === dcLookupId) { disconnectInstances.push(dcUser); } } if (disconnectInstances.length > 0) { resp = u.getUser().username + ' has disconnected ' + disconnectInstances.length.toString() + ' time'; if (disconnectInstances.length === 1) { resp += '. '; } else { resp += 's. '; } recentDisconnect = disconnectInstances.pop(); dcHour = recentDisconnect.time.getHours(); dcMins = recentDisconnect.time.getMinutes(); if (dcMins < 10) { dcMins = '0' + dcMins.toString(); } dcMeridian = dcHour % 12 === dcHour ? 'AM' : 'PM'; dcTimeStr = '' + dcHour + ':' + dcMins + ' ' + dcMeridian; dcSongsAgo = data.songCount - recentDisconnect.songCount; resp += 'Their most recent disconnect was at ' + dcTimeStr + ' (' + dcSongsAgo + ' songs ago). '; if (recentDisconnect.waitlistPosition !== void 0) { resp += 'They were ' + recentDisconnect.waitlistPosition + ' song'; if (recentDisconnect.waitlistPosition > 1) { resp += 's'; } resp += ' away from the DJ booth.'; } else { resp += 'They were not on the waitlist.'; } API.sendChat(resp); return; } else { API.sendChat("I haven't seen " + u.getUser().username + " disconnect."); return; } } } return API.sendChat("I don't see a user in the room named '" + givenName + "'."); } }; return disconnectLookupCommand; })(Command); voteRatioCommand = (function(_super) { __extends(voteRatioCommand, _super); function voteRatioCommand() { _ref29 = voteRatioCommand.__super__.constructor.apply(this, arguments); return _ref29; } voteRatioCommand.prototype.init = function() { this.command = '!voteratio'; this.parseType = 'startsWith'; return this.rankPrivelege = 'mod'; }; voteRatioCommand.prototype.functionality = function() { var msg, name, r, u, votes; r = new RoomHelper(); msg = this.msgData.message; if (msg.length > 12) { name = msg.substr(12); u = r.lookupUser(name); if (u !== false) { votes = r.userVoteRatio(u); msg = u.username + " has wooted " + votes['woot'].toString() + " time"; if (votes['woot'] === 1) { msg += ', '; } else { msg += 's, '; } msg += "and meh'd " + votes['meh'].toString() + " time"; if (votes['meh'] === 1) { msg += '. '; } else { msg += 's. '; } msg += "Their woot:vote ratio is " + votes['positiveRatio'].toString() + "."; return API.sendChat(msg); } else { return API.sendChat("I don't recognize a user named '" + name + "'"); } } else { return API.sendChat("I'm not sure what you want from me..."); } }; return voteRatioCommand; })(Command); avgVoteRatioCommand = (function(_super) { __extends(avgVoteRatioCommand, _super); function avgVoteRatioCommand() { _ref30 = avgVoteRatioCommand.__super__.constructor.apply(this, arguments); return _ref30; } avgVoteRatioCommand.prototype.init = function() { this.command = '!avgvoteratio'; this.parseType = 'exact'; return this.rankPrivelege = 'mod'; }; avgVoteRatioCommand.prototype.functionality = function() { var averageRatio, msg, r, ratio, roomRatios, uid, user, userRatio, votes, _i, _len, _ref31; roomRatios = []; r = new RoomHelper(); _ref31 = data.voteLog; for (uid in _ref31) { votes = _ref31[uid]; user = data.users[uid].getUser(); userRatio = r.userVoteRatio(user); roomRatios.push(userRatio['positiveRatio']); } averageRatio = 0.0; for (_i = 0, _len = roomRatios.length; _i < _len; _i++) { ratio = roomRatios[_i]; averageRatio += ratio; } averageRatio = averageRatio / roomRatios.length; msg = "Accounting for " + roomRatios.length.toString() + " user ratios, the average room ratio is " + averageRatio.toFixed(2).toString() + "."; return API.sendChat(msg); }; return avgVoteRatioCommand; })(Command); cmds = [cookieCommand, newSongsCommand, whyWootCommand, themeCommand, rulesCommand, roomHelpCommand, sourceCommand, wootCommand, badQualityCommand, downloadCommand, afksCommand, allAfksCommand, statusCommand, unhookCommand, dieCommand, reloadCommand, lockCommand, unlockCommand, swapCommand, popCommand, pushCommand, overplayedCommand, uservoiceCommand, whyMehCommand, skipCommand, commandsCommand, resetAfkCommand, forceSkipCommand, disconnectLookupCommand, voteRatioCommand, avgVoteRatioCommand]; chatCommandDispatcher = function(chat) { var c, cmd, _i, _len, _results; chatUniversals(chat); _results = []; for (_i = 0, _len = cmds.length; _i < _len; _i++) { cmd = cmds[_i]; c = new cmd(chat); if (c.evalMsg()) { break; } else { _results.push(void 0); } } return _results; }; updateVotes = function(obj) { data.currentwoots = obj.positive; data.currentmehs = obj.negative; return data.currentcurates = obj.curates; }; announceCurate = function(obj) { return API.sendChat("/em: " + obj.user.username + " loves this song!"); }; handleUserJoin = function(user) { data.userJoin(user); data.users[user.id].updateActivity(); return API.sendChat("/em: " + user.username + " has joined the Room!"); }; handleNewSong = function(obj) { var songId; data.intervalMessages(); if (data.currentsong === null) { data.newSong(); } else { API.sendChat("/em: Just played " + data.currentsong.title + " by " + data.currentsong.author + ". Stats: Woots: " + data.currentwoots + ", Mehs: " + data.currentmehs + ", Loves: " + data.currentcurates + "."); data.newSong(); document.getElementById("button-vote-positive").click(); } if (data.forceSkip) { songId = obj.media.id; return setTimeout(function() { var cMedia; cMedia = API.getMedia(); if (cMedia.id === songId) { return API.moderateForceSkip(); } }, obj.media.duration * 1000); } }; handleVote = function(obj) { data.users[obj.user.id].updateActivity(); return data.users[obj.user.id].updateVote(obj.vote); }; handleUserLeave = function(user) { var disconnectStats, i, u, _i, _len, _ref31; disconnectStats = { id: user.id, time: new Date(), songCount: data.songCount }; i = 0; _ref31 = data.internalWaitlist; for (_i = 0, _len = _ref31.length; _i < _len; _i++) { u = _ref31[_i]; if (u.id === user.id) { disconnectStats['waitlistPosition'] = i - 1; data.setInternalWaitlist(); break; } else { i++; } } data.userDisconnectLog.push(disconnectStats); return data.users[user.id].inRoom(false); }; antispam = function(chat) { var plugRoomLinkPatt, sender; plugRoomLinkPatt = /(\bhttps?:\/\/(www.)?plug\.dj[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; if (plugRoomLinkPatt.exec(chat.message)) { sender = API.getUser(chat.fromID); if (!sender.ambassador && !sender.moderator && !sender.owner && !sender.superuser) { if (!data.users[chat.fromID]["protected"]) { API.sendChat("Don't spam room links you ass clown"); return API.moderateDeleteChat(chat.chatID); } else { return API.sendChat("I'm supposed to kick you, but you're just too darn pretty."); } } } }; beggar = function(chat) { var msg, r, responses; msg = chat.message.toLowerCase(); responses = ["Good idea @{beggar}! Don't earn your fans or anything thats so yesterday", "Guys @{beggar} asked us to fan him! Lets all totally do it! ಠ_ಠ", "srsly @{beggar}? ಠ_ಠ", "@{beggar}. Earning his fans the good old fashioned way. Hard work and elbow grease. A true american."]; r = Math.floor(Math.random() * responses.length); if (msg.indexOf('fan me') !== -1 || msg.indexOf('fan for fan') !== -1 || msg.indexOf('fan pls') !== -1 || msg.indexOf('fan4fan') !== -1 || msg.indexOf('add me to fan') !== -1) { return API.sendChat(responses[r].replace("{beggar}", chat.from)); } }; chatUniversals = function(chat) { data.activity(chat); antispam(chat); return beggar(chat); }; hook = function(apiEvent, callback) { return API.on(apiEvent, callback); }; unhook = function(apiEvent, callback) { return API.off(apiEvent, callback); }; apiHooks = [ { 'event': API.ROOM_SCORE_UPDATE, 'callback': updateVotes }, { 'event': API.CURATE_UPDATE, 'callback': announceCurate }, { 'event': API.USER_JOIN, 'callback': handleUserJoin }, { 'event': API.DJ_ADVANCE, 'callback': handleNewSong }, { 'event': API.VOTE_UPDATE, 'callback': handleVote }, { 'event': API.CHAT, 'callback': chatCommandDispatcher }, { 'event': API.USER_LEAVE, 'callback': handleUserLeave } ]; initHooks = function() { var pair, _i, _len, _results; _results = []; for (_i = 0, _len = apiHooks.length; _i < _len; _i++) { pair = apiHooks[_i]; _results.push(hook(pair['event'], pair['callback'])); } return _results; }; undoHooks = function() { var pair, _i, _len, _results; _results = []; for (_i = 0, _len = apiHooks.length; _i < _len; _i++) { pair = apiHooks[_i]; _results.push(unhook(pair['event'], pair['callback'])); } return _results; }; initialize(); }).call(this);
hybridables / Handle ArgumentsGet separately non-callback arguments in `.arguments` and the last argument if it `is-callback-function` in `.callback` property. It also works like `sliced`, but returns object with `.arguments` and `.callback` properties.
BholaHrishikesh / Psychic Rotary PhoneIf you like this build I’ve also written other posts on building a simple voice controlled Magic Mirror with the Raspberry Pi and the AIY Projects Voice Kit, and a face-tracking cyborg dinosaur called “Do-you-think-he-saurs” with the Raspberry Pi and the AIY Projects Vision Kit. At the tail end of last month, just ahead of the announcement of the pre-order availability of the new Google AIY Project Voice Kit, I finally decided to take the kit I’d managed to pick up with issue 57 of the MagPi out of its box, and put it together. However inspired by the 1986 Google Pi Intercom build put together Martin Mander, ever since I’ve been thinking about venturing beyond the cardboard box and building my own retro-computing enclosure around the Voice Kit. I was initially thinking about using an old radio until I came across the GPO 746 Rotary Telephone. This is a modern day replica of what must be the most iconic rotary dial phone in the United Kingdom. This is the phone that sat on everybody’s desk, and in their front halls, throughout the 1970’s. It was the standard rental phone, right up until British Telecom was privatised in the middle of the 1980's. The GPO 746 Rotary Telephone. While the GPO 746 is available in the United States it’s half the price, and there are a lot more colours to choose from, if you’re buying the phone in the United Kingdom. A definite business opportunity for someone there because it turns out that, on the inside, it’s a rather interesting bit of hardware. Gathering your Tools For this project you’ll need is a small Philips “00” watch maker’s screwdriver, a craft knife, scissors, a set of small wire snips, a drill and a 2 to 4mm bit, a soldering iron, solder, some jumper wires, female header blocks, a couple of LEDs, some electrical tape, a cable tie, and possibly some Sugru and heat shrink tubing, depending how neat you want to be about things. While I did end up soldering a few things during the build, it is was mostly restricted to joining wires together and should definitely be approachable for beginners. Opening the Box Ahead of the new Voice Kit hitting the shelves next month I managed to get my hands on a few pre-production kits, which fortunately meant that I didn’t have to take my cardboard box apart to put together a new build. The new AIY Project Voice Kit. The new AIY Voice Kit comes comes in a box very similar to the original kit distributed with the Mag Pi magazine. The box might be a bit thinner, but otherwise things look much the same. Missing from my pre-production kits the two little plastic spacers that keep the Voice HAT from bending down and hitting the top of the Raspberry Pi. I’m presuming they’ll include them in the production kits, without them the underside of the HAT tends to push downwards and the solder tails of the speaker screw terminal shorts out against the Raspberry Pi’s HDMI connector. I fixed this by adding some electrical tape to separate the two boards, but the spacers would have worked a lot better and added more stability. The only component swap was the arcade button, gone was the separate lamp, holder, microswitch and button—all four components have been replaced by a single button with everything integrated. Since it was somewhat fiddly to get that assembled last time, this is a definite improvement. While my pre-production kits didn’t include it, I’m told the retail version will have a copy of the MagPi Essentials AIY Projects book written by Lucy Hattersley on how to “Create a Voice Kit with your Raspberry Pi.” Other than that, things went together much as before. At which point I quickly put together the Voice Kit, this time however, I didn’t bother with the cardboard box. Opening the Phone Pulling the replica GPO 746 out of its box you’ll find it comes in two parts, the main phone with the dial, and a separate handset which plugs in underneath the base. The first thing I needed to do was take the base unit of the phone apart and figure out how it worked. Until I knew what I had to work with, it was going to be impossible to figure out a sensible plan to integrate the Voice Kit. Opening up the GPO 746. The main PCB is mounted on the base along with a steel weight to give the impression of “heft” to the replica phone. There’s also a large bell, which makes that distinctive ringing noise familiar to anyone that owned or used a GPO 746 back in the 1970's. The circuitry attached to the base of the GPO 746. To the left of the PCB is the jack socket where the telephone line is connected (two wires, red and green). To the top, two switches. One is for handset, and the other for ringer, volume. At the bottom another jack switch (four wires, red, black, yellow, and green) where the handset is attached. The only thing of real interest on the PCB is the Hualon Microelectronics HM9102D which is a switchable tone/pulse dialer chip, which we’re actually not going to use. In fact, since the line voltage in the UK is +50V, pretty much none of it was going to be any use to me. So after measuring the voltage on the cable connecting the dialer to the PCB, I snipped the wires to the switches and the jacks—leaving them in place with as much trailing wire as possible in case they were going to come in useful,—and then removed both the PCB and the bell. After that, I filed down the plastic moulding that held everything in place leaving me with a large flat area which was perfectly sized for the Raspberry Pi and the Voice HAT. The moulded top of the phone has two assemblies, a simple microswitch toggled using a hinged and sprung plastic plate when the phone handset is taken on and off the hook, and the dialer assembly which is connected to the base and the PCB using a ribbon cable. How the Dialer Works It was time to break out the logic analyser. While I’ve got a Saleae Logic Pro 16 on my desk, if you’re thinking about picking one up for the first time I’d really recommend the much cheaper Logic 8, or even the lower specification Logic 4, rather than splashing out on the higher end model. Either will take you a long way before you get the itch that you have to upgrade. Logic Analyser attached to the dial of the GPO 746 powered up using a Bench Power Supply. Stripping the connector from the cable that connected the dialer to the PCB and powering it up with a bench power supply to +5V—which is more-or-less what I’d measured on the cable and was something I could reasonably expect to get from the Raspberry Pi—I connected the rest of the cables to my logic analyser and started turning the dial confidently expecting to see something interesting going on. I found nothing, I had flat lines, there was no signal going down the wires at all. After playing around with the voltage for a few minutes, with no results, I stripped the dialer assembly out of the case for a closer look. Dialer assembly removed from the GPO 746. The back of the dialer assembly has two LEDs, which I thought was rather odd since there dial isn’t illuminated in any way, at least not from the outside. Interestingly these two LEDs flash briefly when the dial is turned all the way around to hit the stop. Cracking the case brings us to something else interesting, it’s a light box. Designed to keep the light from the LEDs inside, it has a hole which rotates around as you dial a number. Taking apart the dial assembly. The hole exposes one of twelve photoresistors to the light from the LEDs and the number (or symbol) you’re dialing determines which of the resistors will be under the hole when the dial stop is reached. The photoresistors inside the dial assembly. It was all passive circuitry. No wonder I hadn’t seen anything on the logic analyser, there wasn’t any logic to analyse. It was all analogue. Unfortunately for me, the Raspberry Pi has no built in analogue inputs. That means I’d have to pull a Microchip MCP3008, or something similar, from the shelf and build some circuitry. I’d also have to figure out how the resistance for twelve photoresistors ended up travelling down just eight wires, which sort of had me puzzled at this point. That all sounded like a lot of effort. Since I really only wanted to dial a single digit to activate the Voice Kit, and I didn’t care what that was, I decided to ignore the photoresistors and concentrate on the dial stop. The dialer mechanism showing the back of the dial stop (left) with microswitch. Unlike the original GPO 746, the dial stop on this replica moves. It drops when you hit it with the side of your finger when dialling a number. It turned out that it was connected to a microswitch, and when the microswitch was activated, this was the thing that briefly flashed the LEDs and exposed the appropriate photoresistor. It was actually all rather clever. A really neat way to minimise the build of materials costs for the phone. Startups thinking about building hardware could learn a lesson or two in economy from this phone. Using the logic analyser on the microswitch. Just to be sure I had this right, I dialled down the bench power supply to a Raspberry Pi friendly +3.3V and wired up the microswitch to the logic analyser. Applying +3.3V (middle trace) and “dialing” shows the microswitch toggling (lower trace). Dialling a number on the dialer assembly worked as expected. We could ignore the dial itself, and those photoresistors that would be a pain to use with the Raspberry Pi and just make use of the microswitch. In fact we could more-or-less just replace the arcade button with this switch. Integrating the AIY Project Kit Moving on, I really wanted to reuse both the speaker and the microphone already in the handset instead of the ones the came with the Voice Kit. Handset stripped of its speaker and micrphone, Taking apart the handset—the end caps holding the speaker and microphone just screw off—showed that there were four wires inside the curled cable. Two for the speaker, and two for the electret condenser microphone. The Voice Kit makes use of two InvenSense ICS-43434 MEMS microphones which use I2S to communicate. They’re a solid replacement for traditional 2-wire analog microphones like the one we in the handset of the GPO 746. The Voice HAT Microphone daughter board. Looking at the Voice HAT microphone daughter board, it has been designed so that you can break the two microphones away from the board at the perforations and then you can solder the wiring harness directly to the pads. So long as you keep the signals consistent you should be able to place the mics pretty much anywhere, and with a clock rate of ~3MHz, a longer cable should be fine. Unfortunately I2S uses more wires than I had available. Unless I wanted to replace the curled cable, and I didn’t really want to have to do that, I was in trouble. Putting that aside for a moment I decided to start with the dialer assembly. Refitting it to the case, I snipped the wires leading to the microswitch and, grabbing the wiring harness for the arcade button, I soldered the microswitch to the relevant wires in the harness. Soldering the Voice HAT button wiring harness to the phone’s microswitch. I then grabbed a ultra-bright LED and a 220Ω resistor from the shelves and soldered the resistor in-line with the LED. I then attached my new LED assembly to the other two wires in the arcade button wiring harness. At this point I had a replacement for the arcade button that came with the Voice Kit. Attaching a current limiting resistor to my LED. Giving up on putting microphones into the handset I pulled out a drill and measuring the spacing between the two microphones I drilled a couple of holes in the external shell of the phone. Drilling two holes in the shell of the phone. These weren’t going to be visible from the outside as there is a void between the top of the phone, where the handset rests. This is a carrying handle where you can tuck your hand in, and pick up the phone. In the old days this let you pick up the phone and wander around the room—well, so long as the cable tying you to the wall was long enough. Attaching the Voice HAT microphone board to the phone shell. I then went ahead and tucked the microphone board behind the spring which operated the hook mechanism. There was just enough room to secure it there with a cable tie, and some Sugru. After that I plugged the handset into the jack on the base and connected the two wires from the handset jack that were attached to the speaker to the screw terminals on the Voice HAT. The re-wired internals of the modified GPO 746. Microphone board and Voice Kit both fixed in place with Sugru. Stripping the jack out where the phone line originally ran left two upright pillars that used to go on either side of the jack. I threaded the end of a 2.5A micro-USB charger through the hole and tied it around the pillars for strain relief. Which completed the re-wiring. The arcade button had been replaced with the dial stop microswitch and an LED which I was going to tuck just ahead of the microphone board in a convenient clip-like part of the body moulding. The speaker had been swapped out directly with the one in the handset—fortunately the impedance match wasn’t too far off—and the microphone had been mounted somewhere convenient inside the main body of the phone. A Working Phone Screwing everything back together we have once again something that looks like a phone. The assembled phone. I booted the Raspberry Pi, logged in via SSH and went ahead and ran the src/assistant_library_with_button_demo.py script from the dev console. A working build, but it’s not quite there yet. Success. Picking up the handset and dialling a number, any number, let you talk to the Voice Assistant. But it wasn’t quite there yet. While it worked, it didn’t feel like a phone. Adding a Dial Tone What the phone needed was a dial tone. It needed to play when the handset was lifted and shut off when the phone was dialled, or the handset replaced. The phone hook works the opposite way that you might expect, when the handset is in the cradle the microswitch that simulates the hook is open as the bar below it is pushed down by the hook. When the handset is off the hook, then the microswitch is closed as the bar moves upwards. Conveniently the Voice HAT breaks out most of the unused GPIO pins from the Raspberry Pi, so at least in theory wiring the the microswitch attached to the the hook mechanism to one to the Voice HAT should be fairly simple. Available unpopulated connectors on the Voice HAT. (Image credit: Google) Thinking about how to approach this in software however left us with a bit of a quandary. While the underlying Python GPIO library allows us to detect both the rising and falling edge events when a switch is toggled, the AIY wrapper code doesn’t in the Voice Kit doesn’t. While I could have gone in and modified the wrapper code to add that functionality, I decided I didn’t want to mess around with that—perhaps I’ll get around to it later and send them a pull request—instead I decided to fix it in hardware and wire the hook switch into both GPIO4 and GPIO17. That way I could use one pin to monitor for GPIO.RISING, and the other for GPIO.FALLING. Wiring up the phone hook. It’s easy enough to do that using the aiy._drivers._button.Button class, and two callback methods. One called with the handset is taken off the hook, and the other called with it is replaced. All the additional wiring in place and working. We can then use the pygame library to play a WAV file in the background when the handset is lifted, and stop when it is replaced. We also have to add a stop command inside the _on_button_pressed() method so that the dial tone stops when the phone is dialled, and a call to stop_conversation() to stop the Voice Assistant talking if the handset is returned on hook while Google is answering our question. Adding a Greeting and a Hang Up Noise We’re not quite there yet, we can also use aiy.audio.play_wave() to add that distinctive disconnect noise when Google finishes talking and “hangs up” before returning to our dial tone. We can also use aiy.audio.say(‘…’) call to add a greeting when Google “picks up” the phone to talk to us. The final build. It’s surprising how much atmosphere just adding these simple sounds ended up making to the build, and how much the user experience was improved. It now doesn’t just look like a rotary phone, it sort of feels, and perhaps more importantly, sounds like one too. The Script The final version of the script has amazingly small number of modifications away from the original version distributed byGoogle. Which sort of shows how simple it is to build something that looks and feels very different from the original cardboard box with not a lot of effort, at least on the software If you want to replicate the build you can grab the two mono WAV files I used for the build from Dropbox. Although, if you’re outside the the United Kingdom, you might want to replace the standard British dial tone of 350Hz and 450Hz—which you hear any time you lift a phone off the hook—with something more appropriate. Available to Preorder The new kits are being produced by Google, and are available to pre-order at Micro Center and through their resellers like Adafruit, and SeeedStudio. The AIY Voice Kit is priced at $25 on its own, but you can pick one up for free if you order a Raspberry Pi 3 at $35 for in-store pickup from Micro Center. My new retro rotary phone build next to my original Voice Kit. The kit will be available in the United Kingdom through Pimoroni, and cost £25, and you can expect shipping dates for kits ordered in through them to be similar to those ordered from Micro Center.