Исходник Софт luajit-request - упрощенная работа с http(s)-запросами

stool

Известный
Автор темы
353
258
однажды задался вопросом о том, как легко и просто без лишних мыслей просто взять и скачать картинку прямо в память скрипта и работать с ней в качестве текстурки. не найдя быстрого способа на форуме, нашел его сам и адаптировал, чем делюсь с вами. эта шляпа позволяет прям из интернета скачивать файлы в память, не оставляя их на компе. (основная задача либы это в принципе работа с запросами, можно странички парсить в две строки)

украл либу отсюда: https://github.com/LPGhatguy/luajit-request
скачал libcurl (зависимость), подредактировал init.lua (чтобы либа не искала libcurl)
установка: положить папку lib из архива в папку moonloader
1718670528633.png

пример использования:
local request = require("luajit-request")
local memory = require("memory")

local txt
local response

function main()
    while not isSampAvailable() do wait(0) end
    response = request.send("https://i.imgur.com/H7D2PMm.png") -- отправляем запрос
    if response.code==200 and response then -- если всё успешно
        -- то подгружаем png-картинку как текстуру
        txt = renderLoadTextureFromFileInMemory(memory.strptr(response.body), #response.body)
    end
    while true do
        -- рисуем скачанную картинку
        renderDrawTexture(txt, 0, 0, 100, 100, 0, 0xffffffff)
        wait(0)
    end
end

Simple GET:
local request = require("luajit-request")
local response = request.send("https://example.com")

print(response.code)
print(response.body)
Digest Authentication and Cookies:
local request = require("luajit-request")

local response = request.send("https://example.com", {
    cookies = {
        hello = "world"
    },

    auth_type = "digest",
    username = "user",
    password = "pass"
})

print(response.body)
print(response.set_cookies)
Forms:
local request = require("luajit-request")

local response = request.send("https://example.com", {
    method = "POST",
    data = {
        hello = "world"
    }
})

print(response.code)
print(response.body)
Stream file (2.3+):
local request = require("luajit-request")

local result, err, message = request.send("https://www.posttestserver.com/post.php", {
    method = "POST",
    files = {
        readme = "README.md"
    }
})

if (not result) then
    print(err, message)
end

print(result.body)
Send an HTTP(S) request to the URL at 'url' using the HTTP method 'method'.
Use the 'args' parameter to optionally configure the request:
- method: HTTP method to use. Defaults to "GET", but can be any HTTP verb like "POST" or "PUT"
- headers: Dictionary of additional HTTP headers to send with request
- data: Dictionary or string to send as request body
- cookies: Dictionary table of cookies to send
- timeout: How long to wait for the connection to be made before giving up
- allow_redirects: Whether or not to allow redirection. Defaults to true
- body_stream_callback: A method to call with each piece of the response body.
- header_stream_callback: A method to call with each piece of the resulting header.
- transfer_info_callback: A method to call with transfer progress data.
- auth_type: Authentication method to use. Defaults to "none", but can also be "basic", "digest" or "negotiate"
- username: A username to use with authentication. 'auth_type' must also be specified.
- password: A password to use with authentication. 'auth_type' must also be specified.
- files: A dictionary of file names to their paths on disk to upload via stream.

If both body_stream_callback and header_stream_callback are defined, a boolean true will be returned instead of the following object.

The return object is a dictionary with the following members:
- code: The HTTP status code the response gave. Will not exist if header_stream_callback is defined above.
- body: The body of the response. Will not exist if body_stream_callback is defined above.
- headers: A dictionary of headers and their values. Will not exist if header_stream_callback is defined above.
- headers_raw: A raw string containing the actual headers the server sent back. Will not exist if header_stream_callback is defined above.
- set_cookies: A dictionary of cookies given by the "Set-Cookie" header from the server. Will not exist if the server did not set any cookies.

If an error occured, false will be returned along with a curl error code and a message.
 

Вложения

  • luajit-request (moonloader support).zip
    1.4 MB · Просмотры: 51

зач хейт

Потрачен
115
46
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
однажды задался вопросом о том, как легко и просто без лишних мыслей просто взять и скачать картинку прямо в память скрипта и работать с ней в качестве текстурки. не найдя быстрого способа на форуме, нашел его сам и адаптировал, чем делюсь с вами. эта шляпа позволяет прям из интернета скачивать файлы в память, не оставляя их на компе. (основная задача либы это в принципе работа с запросами, можно странички парсить в две строки)

украл либу отсюда: https://github.com/LPGhatguy/luajit-request
скачал libcurl (зависимость), подредактировал init.lua (чтобы либа не искала libcurl)
установка: положить папку lib из архива в папку moonloader
Посмотреть вложение 243768
пример использования:
local request = require("luajit-request")
local memory = require("memory")

local txt
local response

function main()
    while not isSampAvailable() do wait(0) end
    response = request.send("https://i.imgur.com/H7D2PMm.png") -- отправляем запрос
    if response.code==200 and response then -- если всё успешно
        -- то подгружаем png-картинку как текстуру
        txt = renderLoadTextureFromFileInMemory(memory.strptr(response.body), #response.body)
    end
    while true do
        -- рисуем скачанную картинку
        renderDrawTexture(txt, 0, 0, 100, 100, 0, 0xffffffff)
        wait(0)
    end
end

Simple GET:
local request = require("luajit-request")
local response = request.send("https://example.com")

print(response.code)
print(response.body)
Digest Authentication and Cookies:
local request = require("luajit-request")

local response = request.send("https://example.com", {
    cookies = {
        hello = "world"
    },

    auth_type = "digest",
    username = "user",
    password = "pass"
})

print(response.body)
print(response.set_cookies)
Forms:
local request = require("luajit-request")

local response = request.send("https://example.com", {
    method = "POST",
    data = {
        hello = "world"
    }
})

print(response.code)
print(response.body)
Stream file (2.3+):
local request = require("luajit-request")

local result, err, message = request.send("https://www.posttestserver.com/post.php", {
    method = "POST",
    files = {
        readme = "README.md"
    }
})

if (not result) then
    print(err, message)
end

print(result.body)

1718684107273.png
ааааблин сложно блябуду
 
  • Нравится
Реакции: Mintha

Rice.

известный клоун
Модератор
1,734
1,588
просто взять и скачать картинку прямо в память скрипта и работать с ней в качестве текстурки
Lua:
local response = requests.get('site')
local image = imgui.CreateTextureFromFileInMemory(memory.strptr(response.text), #response.text)
 
  • Нравится
Реакции: Mintha, The Spark и stool

CaJlaT

Овощ
Модератор
2,819
2,639
Чо по асинхронности? (Лень сурсы либы чекать)
 

stool

Известный
Автор темы
353
258
Чо по асинхронности? (Лень сурсы либы чекать)
отсутствует

Чо по асинхронности? (Лень сурсы либы чекать)
либа проще некуда, используется ТОЛЬКО libcurl, насколько возможно использовать либу в асинхре -> не могу достоверно знать, так как единственная цель у меня была это отправить запрос, получить ответ и тело ответа положить в текстурку.
если с lua_threads будет работать нормально, то можно будет считать, что асинк есть)0
 
  • Грустно
Реакции: CaJlaT

ferzin

Потрачен
47
28
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
  • Вау
Реакции: stool