Skip to content

Instantly share code, notes, and snippets.

@Amaimersion
Created July 10, 2018 09:50
Show Gist options
  • Save Amaimersion/0960d096af42f9ab8126b1c755902067 to your computer and use it in GitHub Desktop.
Save Amaimersion/0960d096af42f9ab8126b1c755902067 to your computer and use it in GitHub Desktop.
Функции для создания треда, взятые с 2ch.hk. Версия кэша swag – 35, MD5 всего файла swag – 13d9757cc5e9c9bb5128ec9d48df84c1
/**
* Взято не из файла `swag.js`. Это просто моя заметка.
*
* Это пример полного (?) `FormData` объекта.
* Все записи, полученные с помощью функции `FormData.entries()`:
*
* @example
* > (2) ["task", "post"] // `<input type="hidden" name="task" value="post">`
* > (2) ["board", "pr"] // `<input type="hidden" name="board" value="pr">`
* > (2) ["thread", "0"] // `<input type="hidden" name="thread" value="0">`
* > (2) ["usercode", ""] // `<input type="hidden" name="usercode" value="" id="usercode-input" class="usercode-input">`
* > (2) ["code", ""] // `<input class="mod-code-input" type="hidden" value="" name="code">`
* > (2) ["captcha_type", "invisible_recaptcha"] // `<input type="hidden" name="captcha_type" value="invisible_recaptcha">`
* > (2) ["email", "sage"] // опции. `<input id="e-mail" type="text" value="" name="email" size="30" placeholder="опции">`
* > (2) ["name", "Sergey Kuznetsov"] // имя. `<input type="text" value="" id="name" name="name" size="30" placeholder="имя">`
* > (2) ["subject", "Test"] // тема. `<input type="text" maxlength="150" id="subject" name="subject" placeholder="тема">`
* > (2) ["tags", "tag"] // тег. `<input type="text" maxlength="8" id="tags" name="tags" placeholder="макс 8 символов">`
* > (2) ["comment", "Some test for 2ch-helper."] // пост. `<textarea name="comment" id="shampoo" rows="10" placeholder="Комментарий. Макс. длина 15000"></textarea>`
* > (2) ["formimages[]", File(0)] // изображения. `<input type="file" name="formimages[]" id="formimages" class="form-files-input-multi" multiple="">`
* > (2) ["2chaptcha_id", ""] // `<input type="hidden" name="2chaptcha_id" class="captcha-key">`
*/
$forms.on("submit", function() {
if (typeof FormData == "undefined") return; //старый браузер
if (busy) {
request.abort();
return false;
}
window.FormFiles.appendToForm(this);
var form = $(this);
saveToStorage();
var widgetQr;
var renderCaptcha = function() {
var key = window.config.captchaKey;
if (key == -1 || key == -2) {
sendForm(form[0]);
} else {
$(".captcha__key").val(key);
if ($("#captcha-widget").html() == "") {
//проверка капчи до отправки файлов
//@todo
renderCaptchaResolve();
widgetQr = grecaptcha.render("captcha-widget", {
sitekey: key,
theme: "light",
size: "invisible",
callback: function(r) {
//var r = grecaptcha.getResponse();
var e = document.getElementById("captcha-widget-main");
e.innerHTML = "";
var input = document.createElement("input");
input.type = "hidden";
input.name = "g-recaptcha-response";
input.value = r;
e.appendChild(input);
sendForm(form[0]);
}
});
grecaptcha.execute(widgetQr);
} else {
renderCaptchaResolve();
grecaptcha.reset(widgetQr);
grecaptcha.execute(widgetQr);
}
}
};
if (Store.get("other.captcha_provider", "google") == "2chaptcha") {
sendForm(form[0]);
} else if (validateForm(form.attr("id") == "qr-postform")) {
renderCaptcha();
}
return false;
});
var sendForm = function(form) {
if (FormFiles.vip || FormFiles.channelvip) $(".form-files-input-multi").val("");
var formData = new FormData(form);
busy = true;
//эта пипка для подмены пикч, если из мультиселекта было что-то удалено
if (FormFiles.vip) {
if (typeof formData.delete === "function") formData.delete("formimages[]");
for (var i = 0, len = FormFiles.filtered.length; i < len; i++) {
formData.append("formimages[]", FormFiles.filtered[i]);
}
}
request = $.ajax({
url: "/makaba/posting.fcgi?json=1", //Server script to process data
type: "POST",
dataType: "json",
xhr: function() {
// Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// Check if upload property exists
myXhr.upload.addEventListener("progress", progressHandling, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: on_send_success,
error: on_send_error,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
renderSending();
};
var renderSending = function() {
/*var inputs = forms.find('input,select,textarea').not('[type=submit]');
inputs.attr('disabled','disabled');*/
$submit_buttons.attr("value", "Отправка...");
};
var renderSendingDone = function() {
/*var inputs = forms.find('input,select,textarea').not('[type=submit]');
inputs.removeAttr('disabled');*/
$submit_buttons.attr("value", "Отправить");
};
var progressHandling = function(e) {
var percent = 100 / e.total*e.loaded;
if (percent >= 99) return $submit_buttons.attr('value', 'Обработка...');
var bpercent = ((Math.round(percent * 100)) / 100).toString().split('.');
if(!bpercent[1]) bpercent[1] = 0;
bpercent = (bpercent[0].length == 1 ? '0'+bpercent[0] : bpercent[0]) + '.' + (bpercent[1].length == 1 ? bpercent[1] + '0' : bpercent[1]);
$('#qr-progress-bar').attr('value', e.loaded).attr('max', e.total);
$submit_buttons.attr('value', bpercent + '%');
};
var on_send_error = function(request) {
if (request.statusText == "abort") {
$alert("Отправка сообщения отменена");
} else {
$alert("Ошибка постинга: " + request.statusText);
}
on_complete();
};
var on_send_success = function(data) {
if (data.Error) {
if (data.Id) {
$alert(
data.Reason +
'<br><a href="/ban?Id=' +
data.Id +
'" target="_blank">Подробнее</a>',
"wait"
);
} else {
$alert("Ошибка постинга: " + (data.Reason || data.Error));
if (data.Error == -5) window.postform_validator_error("captcha-value");
}
} else if (data.Status && data.Status == "OK") {
$alert("Сообщение успешно отправлено");
//Favorites если тред && other.autowatchmyposts, то авто-подпись на пост
if (Store.get("other.autowatchmyposts", true) && window.thread.id) {
num = window.thread.id;
if (!Favorites.isFavorited(window.thread.id)) {
Favorites.add(num);
Favorites.show();
Favorites._send_fav(num);
}
current_posts = Store.get("favorites." + num + ".posts", false);
if (current_posts) {
Store.set(
"favorites." + num + ".posts",
current_posts.concat(data.Num)
);
} else {
Store.set("favorites." + num + ".posts", [data.Num]);
}
}
//сохранить номер поста и тред, если включа настройка higlight_myposts
if (Store.get("other.higlight_myposts", true)) {
var num = window.thread.id; //по хорошему это не сработает если постилось в тред с нулевой при включенной опции "не перенаправлять в тред"
current_posts = Store.get(
"myposts." + window.thread.board + "." + num,
[]
);
Store.set(
"myposts." + window.thread.board + "." + num,
current_posts.concat(data.Num)
);
}
if (Store.get("other.qr_close_on_send", true)) $("#qr").hide();
if (!window.thread.id) {
//костыль
var behavior = Store.get("other.on_reply_from_main", 1);
if (behavior == 1) {
window.location.href =
"/" +
window.board +
"/res/" +
$("#qr-thread").val() +
".html#" +
data.Num;
} else if (behavior == 2) {
expandThread(parseInt($("#qr-thread").val()), function() {
Post(data.Num).highlight();
scrollToPost(data.Num);
});
}
} else {
var highlight_num = data.Num;
updatePosts(function(data) {
if (Favorites.isFavorited(window.thread.id))
Favorites.setLastPost(data.data, window.thread.id);
Post(highlight_num).highlight();
//higlight_myposts
//if(Store.get('other.higlight_myposts', true)) Post(highlight_num).highlight_myposts();
});
}
resetInputs();
} else if (data.Status && data.Status == "Redirect") {
var num = data.Target;
$alert("Тред №" + num + " успешно создан");
//костылик, при создании треда для автодобавления в избранное, если есть настройка autowatchmythreads
if (Store.get("other.autowatchmythreads", false))
Store.set("other.mythread_justcreated", true);
window.location.href = "/" + window.board + "/res/" + num + ".html";
} else {
$alert("Ошибка постинга");
}
on_complete();
};
var on_complete = function() {
busy = false;
renderSendingDone();
//loadCaptcha();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment