From 492008d61760ccf23d0b8075a78b5990d2376128 Mon Sep 17 00:00:00 2001
From: mrilyew <99399973+mrilyew@users.noreply.github.com>
Date: Tue, 10 Dec 2024 18:00:14 +0300
Subject: [PATCH] fix js
---
Web/static/js/al_wall.js | 1917 ++++++++++++++++-
...0038-posts-geo.sql => 00051-posts-geo.sql} | 0
2 files changed, 1872 insertions(+), 45 deletions(-)
rename install/sqls/{00038-posts-geo.sql => 00051-posts-geo.sql} (100%)
diff --git a/Web/static/js/al_wall.js b/Web/static/js/al_wall.js
index 66696e29..0706b11a 100644
--- a/Web/static/js/al_wall.js
+++ b/Web/static/js/al_wall.js
@@ -920,54 +920,1881 @@ async function showArticle(note_id) {
u("body").addClass("article");
}
-async function attachNote(id)
-{
- let notes = await API.Wall.getMyNotes()
- let body = ``
+u(document).on("click", "#editPost", async (e) => {
+ const target = u(e.target)
+ const post = target.closest("table")
+ const content = post.find(".post-content")
+ const edit_place = post.find('.post-edit')
+ const id = post.attr('data-id').split('_')
- if(notes.closed < 1) {
- body = `${tr("notes_closed")}`
- } else {
- if(notes.items.length < 1) {
- body = `${tr("no_notes")}`
- } else {
- body = `
- ${tr("select_or_create_new")}
-
`
-
- if(note.value != "none") {
- body += `
-
- ${tr("do_not_attach_note")}
-
`
- }
-
- for(const note of notes.items) {
- body += `
-
- ${escapeHtml(note.name)}
-
- `
- }
-
- body += `
`
- }
+ let type = 'post'
+ if(post.hasClass('comment')) {
+ type = 'comment'
}
- let frame = MessageBox(tr("select_note"), body, [tr("cancel")], [Function.noop]);
+ if(post.hasClass('editing')) {
+ post.removeClass('editing')
+ return
+ }
- document.querySelector(".ovk-diag-body").style.padding = "10px"
+ if(edit_place.html() == '') {
+ target.addClass('lagged')
+ const params = {}
+ if(type == 'post') {
+ params['posts'] = post.attr('data-id')
+ } else {
+ params['owner_id'] = 1
+ params['comment_id'] = id[1]
+ }
+
+ const api_req = await window.OVKAPI.call(`wall.${type == 'post' ? 'getById' : 'getComment'}`, params)
+ const api_post = api_req.items[0]
+
+ edit_place.html(`
+ `)
+
+ if(api_post.copyright) {
+ edit_place.find('.post-source').html(`
+ ${tr('source')}: ${escapeHtml(api_post.copyright.link)}
+
+ `)
+
+ edit_place.find('.post-source #remove_source_button').on('click', (e) => {
+ edit_place.find('.post-source').html('')
+ edit_place.find(`input[name='source']`).attr('value', 'remove')
+ })
+ }
+
+ if(api_post.copy_history && api_post.copy_history.length > 0) {
+ edit_place.find('.post-repost').html(`
+ ${tr('has_repost')}.
+ `)
+ }
+
+ // horizontal attachments
+ api_post.attachments.forEach(att => {
+ const type = att.type
+ const aid = att[type].owner_id + '_' + att[type].id
+
+ if(type == 'video' || type == 'photo') {
+ let preview = ''
+
+ if(type == 'photo') {
+ preview = att[type].sizes[1].url
+ } else {
+ preview = att[type].image[0].url
+ }
+
+ __appendToTextarea({
+ 'type': type,
+ 'preview': preview,
+ 'id': aid
+ }, edit_place)
+ } else if(type == 'poll') {
+ __appendToTextarea({
+ 'type': type,
+ 'alignment': 'vertical',
+ 'html': tr('poll'),
+ 'id': att[type].id,
+ 'undeletable': true,
+ }, edit_place)
+ } else {
+ const found_block = post.find(`div[data-att_type='${type}'][data-att_id='${aid}']`)
+ __appendToTextarea({
+ 'type': type,
+ 'alignment': 'vertical',
+ 'html': found_block.html(),
+ 'id': aid,
+ }, edit_place)
+ }
+ })
+
+ target.removeClass('lagged')
+
+ edit_place.find('.edit_menu #__edit_save').on('click', async (ev) => {
+ const text_node = edit_place.find('.edit_menu textarea')
+ const nsfw_mark = edit_place.find(`.edit_menu input[name='nsfw']`)
+ const as_group = edit_place.find(`.edit_menu input[name='as_group']`)
+ const copyright = edit_place.find(`.edit_menu input[name='source']`)
+ const collected_attachments = collect_attachments(edit_place.find('.post-buttons')).join(',')
+ const params = {}
+
+ params['owner_id'] = id[0]
+ params['post_id'] = id[1]
+ params['message'] = text_node.nodes[0].value
+
+ if(nsfw_mark.length > 0) {
+ params['explicit'] = Number(nsfw_mark.nodes[0].checked)
+ }
+
+ params['attachments'] = collected_attachments
+ if(collected_attachments.length < 1) {
+ params['attachments'] = 'remove'
+ }
+
+ if(as_group.length > 0 && as_group.nodes[0].checked) {
+ params['from_group'] = 1
+ }
+
+ if(copyright.nodes[0].value != 'none') {
+ params['copyright'] = copyright.nodes[0].value
+ }
+
+ u(ev.target).addClass('lagged')
+ // больше двух запросов !
+ try {
+ if(type == 'post') {
+ await window.OVKAPI.call('wall.edit', params)
+ } else {
+ params['comment_id'] = id[1]
+ await window.OVKAPI.call('wall.editComment', params)
+ }
+ } catch(e) {
+ fastError(e.message)
+ u(ev.target).removeClass('lagged')
+ return
+ }
+
+ const new_post_html = await (await fetch(`/iapi/getPostTemplate/${id[0]}_${id[1]}?type=${type}`, {
+ 'method': 'POST'
+ })).text()
+ u(ev.target).removeClass('lagged')
+ post.removeClass('editing')
+ post.nodes[0].outerHTML = u(new_post_html).last().outerHTML
+
+ bsdnHydrate()
+ })
+
+ edit_place.find('.edit_menu #__edit_cancel').on('click', (e) => {
+ post.removeClass('editing')
+ })
+ }
+
+ post.addClass('editing')
+})
+
+async function __uploadToTextarea(file, textareaNode) {
+ const MAX_FILESIZE = window.openvk.max_filesize_mb*1024*1024
+ let filetype = 'photo'
+ if(file.type.startsWith('video/')) {
+ filetype = 'video'
+ }
+
+ if(!file.type.startsWith('image/') && !file.type.startsWith('video/')) {
+ fastError(tr("only_images_accepted", escapeHtml(file.name)))
+ throw new Error('Only images accepted')
+ }
+
+ if(file.size > MAX_FILESIZE) {
+ fastError(tr("max_filesize", window.openvk.max_filesize_mb))
+ throw new Error('Big file')
+ }
+
+ const horizontal_count = textareaNode.find('.post-horizontal > a').length
+ if(horizontal_count > window.openvk.max_attachments) {
+ fastError(tr("too_many_photos"))
+ throw new Error('Too many attachments')
+ }
+
+ const form_data = new FormData
+ form_data.append('photo_0', file)
+ form_data.append('count', 1)
+ form_data.append("hash", u("meta[name=csrf]").attr("value"))
+
+ if(filetype == 'photo') {
+ const temp_url = URL.createObjectURL(file)
+ const rand = random_int(0, 1000)
+ textareaNode.find('.post-horizontal').append(``)
+
+ const res = await fetch(`/photos/upload`, {
+ method: 'POST',
+ body: form_data
+ })
+ const json_response = await res.json()
+ if(!json_response.success) {
+ u(`#temp_filler${rand}`).remove()
+ fastError((tr("error_uploading_photo") + json_response.flash.message))
+ return
+ }
+
+ json_response.photos.forEach(photo => {
+ __appendToTextarea({
+ 'type': 'photo',
+ 'preview': photo.url,
+ 'id': photo.pretty_id,
+ 'fullsize_url': photo.link,
+ }, textareaNode)
+ })
+ u(`#temp_filler${rand}`).remove()
+ URL.revokeObjectURL(temp_url)
+ } else {
+ return
+ }
}
-async function showArticle(note_id) {
- u("body").addClass("dimmed");
- let note = await API.Notes.getNote(note_id);
- u("#articleAuthorAva").attr("src", note.author.ava);
- u("#articleAuthorName").text(note.author.name);
- u("#articleAuthorName").attr("href", note.author.link);
- u("#articleTime").text(note.created);
- u("#articleLink").attr("href", note.link);
- u("#articleText").html(`${note.title}
` + note.html);
- u("body").removeClass("dimmed");
- u("body").addClass("article");
-}
\ No newline at end of file
+async function __appendToTextarea(attachment_obj, textareaNode) {
+ const form = textareaNode.find('.post-buttons')
+ const indicator = textareaNode.find('.post-horizontal')
+
+ if(attachment_obj.alignment == 'vertical') {
+ textareaNode.find('.post-vertical').append(`
+
+
+ ${attachment_obj.html}
+
+
+
+ `)
+
+ return
+ }
+
+ indicator.append(`
+
+ ×
+ ${attachment_obj.type == 'video' ? `` : ''}
+
+
+ `)
+}
+
+u(document).on('paste', '#write .small-textarea', (e) => {
+ if(e.clipboardData.files.length === 1) {
+ __uploadToTextarea(e.clipboardData.files[0], u(e.target).closest('#write'))
+ return;
+ }
+})
+
+u(document).on('dragstart', '#write .post-horizontal .upload-item, .post-vertical .upload-item, .PE_audios .vertical-attachment', (e) => {
+ //e.preventDefault()
+ //console.log(e)
+ u(e.target).closest('.upload-item').addClass('currently_dragging')
+ return
+})
+
+u(document).on('dragover', '#write .post-horizontal .upload-item, .post-vertical .upload-item, .PE_audios .vertical-attachment', (e) => {
+ e.preventDefault()
+
+ const target = u(e.target).closest('.upload-item')
+ const current = u('.upload-item.currently_dragging')
+
+ if(current.length < 1) {
+ return
+ }
+
+ if(target.nodes[0].dataset.id != current.nodes[0].dataset.id) {
+ target.addClass('dragged')
+ }
+
+ return
+})
+
+u(document).on("dragover drop", async (e) => {
+ e.preventDefault()
+ return false;
+})
+
+u(document).on('dragleave dragend', '#write .post-horizontal .upload-item, .post-vertical .upload-item, .PE_audios .vertical-attachment', (e) => {
+ //console.log(e)
+ u(e.target).closest('.upload-item').removeClass('dragged')
+ return
+})
+
+u(document).on("drop", '#write', function(e) {
+ const current = u('.upload-item.currently_dragging')
+ //console.log(e)
+ if(e.dataTransfer.types.includes('Files')) {
+ e.preventDefault()
+
+ e.dataTransfer.dropEffect = 'move'
+ __uploadToTextarea(e.dataTransfer.files[0], u(e.target).closest('#write'))
+ } else if(e.dataTransfer.types.length < 1 || e.dataTransfer.types.includes('text/uri-list')) {
+ e.preventDefault()
+
+ const target = u(e.target).closest('.upload-item')
+ u('.dragged').removeClass('dragged')
+ current.removeClass('currently_dragging')
+ //console.log(target)
+ if(!current.closest('.vertical-attachment').length < 1 && target.closest('.vertical-attachment').length < 1
+ || current.closest('.vertical-attachment').length < 1 && !target.closest('.vertical-attachment').length < 1) {
+ return
+ }
+
+ const first_html = target.nodes[0].outerHTML
+ const second_html = current.nodes[0].outerHTML
+
+ current.nodes[0].outerHTML = first_html
+ target.nodes[0].outerHTML = second_html
+ }
+})
+
+// !!! PHOTO PICKER !!!
+u(document).on("click", "#__photoAttachment", async (e) => {
+ const photos_per_page = 23
+ const form = u(e.target).closest('form')
+ const club = Number(e.currentTarget.dataset.club ?? 0)
+ const msg = new CMessageBox({
+ title: tr('select_photo'),
+ body: `
+
+
+
+
+
+
+
+
+
${tr("is_x_photos", 0)}
+
+
+
+
+ `,
+ buttons: [tr('close')],
+ callbacks: [Function.noop]
+ })
+
+ msg.getNode().attr('style', 'width: 630px;')
+ msg.getNode().find('.ovk-diag-body').attr('style', 'height:335px;padding:0px;')
+
+ async function __recievePhotos(page, album = 0) {
+ u('#gif_loader').remove()
+ u('#attachment_insert').append(``)
+ const insert_place = u('#attachment_insert .photosList')
+ let photos = null
+
+ try {
+ if(album == 0) {
+ photos = await window.OVKAPI.call('photos.getAll', {'owner_id': window.openvk.current_id, 'photo_sizes': 1, 'count': photos_per_page, 'offset': page * photos_per_page})
+ } else {
+ photos = await window.OVKAPI.call('photos.get', {'owner_id': window.openvk.current_id, 'album_id': album, 'photo_sizes': 1, 'count': photos_per_page, 'offset': page * photos_per_page})
+ }
+ } catch(e) {
+ u("#attachment_insert_count h4").html(tr("is_x_photos", -1))
+ u("#gif_loader").remove()
+ insert_place.html("Invalid album")
+ return
+ }
+
+ u("#attachment_insert_count h4").html(tr("is_x_photos", photos.count))
+ u("#gif_loader").remove()
+ const pages_count = Math.ceil(Number(photos.count) / photos_per_page)
+ photos.items.forEach(photo => {
+ const is_attached = (form.find(`.upload-item[data-type='photo'][data-id='${photo.owner_id}_${photo.id}']`)).length > 0
+ insert_place.append(`
+
+
+
+ `)
+ })
+
+ if(page < pages_count - 1) {
+ insert_place.append(`
+
+ ${tr('show_more')}
+
`)
+ }
+ }
+
+ // change album
+ u('.ovk-diag-body .attachment_selector').on("change", ".topGrayBlock #albumSelect", (ev) => {
+ u("#attachment_insert .photosList").html('')
+
+ __recievePhotos(0, ev.target.value)
+ })
+
+ // next page
+ u(".ovk-diag-body .attachment_selector").on("click", "#show_more", async (ev) => {
+ const target = u(ev.target).closest('#show_more')
+ target.addClass('lagged')
+ await __recievePhotos(Number(target.nodes[0].dataset.page), u(".topGrayBlock #albumSelect").nodes[0].value)
+ target.remove()
+ })
+
+ // add photo
+ u(".ovk-diag-body .attachment_selector").on("click", ".album-photo", async (ev) => {
+ ev.preventDefault()
+ ev.stopPropagation()
+
+ const target = u(ev.target).closest('.album-photo')
+ const dataset = target.nodes[0].dataset
+ const is_attached = (form.find(`.upload-item[data-type='photo'][data-id='${dataset.attachmentdata}']`)).length > 0
+ if(is_attached) {
+ (form.find(`.upload-item[data-type='photo'][data-id='${dataset.attachmentdata}']`)).remove()
+ target.removeClass('selected')
+ } else {
+ if(form.find(`.upload-item`).length + 1 > window.openvk.max_attachments) {
+ makeError(tr('too_many_attachments'), 'Red', 10000, 1)
+ return
+ }
+
+ target.addClass('selected')
+ __appendToTextarea({
+ 'type': 'photo',
+ 'preview': dataset.preview,
+ 'id': dataset.attachmentdata,
+ 'fullsize_url': dataset.preview,
+ }, form)
+ }
+ })
+
+ // "upload" button
+ u(".ovk-diag-body #__pickerQuickUpload").on('change', (ev) => {
+ for(file of ev.target.files) {
+ try {
+ __uploadToTextarea(file, form)
+ } catch(e) {
+ makeError(e.message)
+ return
+ }
+ }
+
+ msg.close()
+ })
+
+ __recievePhotos(0)
+ if(!window.openvk.photoalbums) {
+ window.openvk.photoalbums = await window.OVKAPI.call('photos.getAlbums', {'owner_id': club != 0 ? Math.abs(club) * -1 : window.openvk.current_id})
+ }
+ window.openvk.photoalbums.items.forEach(item => {
+ u('.ovk-diag-body #albumSelect').append(``)
+ })
+})
+
+u(document).on('click', '#__videoAttachment', async (e) => {
+ const per_page = 10
+ const form = u(e.target).closest('form')
+ const msg = new CMessageBox({
+ title: tr('selecting_video'),
+ body: `
+
+ `,
+ buttons: [tr('close')],
+ callbacks: [Function.noop]
+ })
+
+ msg.getNode().attr('style', 'width: 630px;')
+ msg.getNode().find('.ovk-diag-body').attr('style', 'height:335px;padding:0px;')
+
+ async function __recieveVideos(page, query = '') {
+ u('#gif_loader').remove()
+ u('#attachment_insert').append(``)
+ const insert_place = u('#attachment_insert .videosInsert')
+ let videos = null
+
+ try {
+ if(query == '') {
+ videos = await window.OVKAPI.call('video.get', {'owner_id': window.openvk.current_id, 'extended': 1, 'count': per_page, 'offset': page * per_page})
+ } else {
+ videos = await window.OVKAPI.call('video.search', {'q': escapeHtml(query), 'extended': 1, 'count': per_page, 'offset': page * per_page})
+ }
+ } catch(e) {
+ u("#gif_loader").remove()
+ insert_place.html("Err")
+ return
+ }
+
+ u("#gif_loader").remove()
+ const pages_count = Math.ceil(Number(videos.count) / per_page)
+
+ if(pages_count < 1) {
+ insert_place.append(query == '' ? tr('no_videos') : tr('no_videos_results'))
+ }
+
+ videos.items.forEach(video => {
+ const pretty_id = `${video.owner_id}_${video.id}`
+ const is_attached = (form.find(`.upload-item[data-type='video'][data-id='${video.owner_id}_${video.id}']`)).length > 0
+ let author_name = ''
+
+ const profiles = videos.profiles
+ const groups = videos.groups
+
+ if(video['owner_id'] > 0) {
+ const profile = profiles.find(prof => prof.id == video['owner_id'])
+ if(profile) {
+ author_name = profile['first_name'] + ' ' + profile['last_name']
+ }
+ } else {
+ const group = groups.find(grou => grou.id == Math.abs(video['owner_id']))
+ if(group) {
+ author_name = group['name']
+ }
+ }
+
+ insert_place.append(`
+
+ `)
+ })
+
+ if(page < pages_count - 1) {
+ insert_place.append(`
+
+ ${tr('show_more')}
+
`)
+ }
+
+ if(query != '') {
+ highlightText(query, '.videosInsert', ['.video-name', '.video-desc'])
+ }
+ }
+
+ u(".ovk-diag-body #video_query").on('change', (ev) => {
+ if(ev.target.value == u(".ovk-diag-body #video_query").nodes[0].value) {
+ u('#attachment_insert .videosInsert').html('')
+ __recieveVideos(0, u(".ovk-diag-body #video_query").nodes[0].value)
+ }
+ })
+
+ // next page
+ u(".ovk-diag-body .attachment_selector").on("click", "#show_more", async (ev) => {
+ const target = u(ev.target).closest('#show_more')
+ target.addClass('lagged')
+ await __recieveVideos(Number(target.nodes[0].dataset.page), u(".topGrayBlock #video_query").nodes[0].value)
+ target.remove()
+ })
+
+ // add video
+ u(".ovk-diag-body .attachment_selector").on("click", "#__attach_vid", async (ev) => {
+ ev.preventDefault()
+
+ const target = u(ev.target).closest('.content')
+ const button = target.find('#__attach_vid')
+ const dataset = target.nodes[0].dataset
+ const is_attached = (form.find(`.upload-item[data-type='video'][data-id='${dataset.attachmentdata}']`)).length > 0
+ if(is_attached) {
+ (form.find(`.upload-item[data-type='video'][data-id='${dataset.attachmentdata}']`)).remove()
+ button.html(tr('attach'))
+ } else {
+ if(form.find(`.upload-item`).length + 1 > window.openvk.max_attachments) {
+ makeError(tr('too_many_attachments'), 'Red', 10000, 1)
+ return
+ }
+
+ button.html(tr('detach'))
+ __appendToTextarea({
+ 'type': 'video',
+ 'preview': dataset.preview,
+ 'id': dataset.attachmentdata,
+ 'fullsize_url': dataset.preview,
+ }, form)
+ }
+ })
+
+ u(".ovk-diag-body .attachment_selector").on('click', '#__fast_video_upload', (ev) => {
+ ev.preventDefault()
+ showFastVideoUpload(form)
+ })
+
+ __recieveVideos(0)
+})
+
+// __audioAttachment -> al_music.js, 1318
+
+u(document).on('click', '#__notesAttachment', async (e) => {
+ const per_page = 10
+ const form = u(e.target).closest('form')
+ const msg = new CMessageBox({
+ title: tr('select_note'),
+ body: `
+
+ `,
+ buttons: [tr("create_note"), tr('close')],
+ callbacks: [() => {
+ window.location.assign('/notes/create')
+ }, Function.noop]
+ })
+
+ msg.getNode().attr('style', 'width: 340px;')
+ msg.getNode().find('.ovk-diag-body').attr('style', 'height:335px;padding:0px;')
+
+ async function __recieveNotes(page) {
+ u('#gif_loader').remove()
+ u('#attachment_insert').append(``)
+ const insert_place = u('#attachment_insert .notesInsert')
+ let notes = null
+
+ try {
+ notes = await window.OVKAPI.call('notes.get', {'user_id': window.openvk.current_id, 'count': per_page, 'offset': per_page * page})
+ } catch(e) {
+ u("#gif_loader").remove()
+ insert_place.html("Err")
+ return
+ }
+
+ u("#gif_loader").remove()
+ const pages_count = Math.ceil(Number(notes.count) / per_page)
+
+ if(notes.count < 1) {
+ insert_place.append(tr('no_notes'))
+ }
+
+ notes.notes.forEach(note => {
+ is_attached = (form.find(`.upload-item[data-type='note'][data-id='${note.owner_id}_${note.id}']`)).length > 0
+ insert_place.append(`
+
+
+
+ ${is_attached ? tr("detach") : tr("attach")}
+
+
+ `)
+ })
+
+ if(page < pages_count - 1) {
+ insert_place.append(`
+
+ ${tr('show_more')}
+
`)
+ }
+ }
+
+ // next page
+ u(".ovk-diag-body .attachment_selector").on("click", "#show_more", async (ev) => {
+ const target = u(ev.target).closest('#show_more')
+ target.addClass('lagged')
+ await __recieveNotes(Number(target.nodes[0].dataset.page))
+ target.remove()
+ })
+
+ // add note
+ u(".ovk-diag-body .attachment_selector").on("click", "#__attach_note", async (ev) => {
+ if(u(form).find(`.upload-item`).length > window.openvk.max_attachments) {
+ makeError(tr('too_many_attachments'), 'Red', 10000, 1)
+ return
+ }
+
+ const target = u(ev.target).closest('._content')
+ const button = target.find('#__attach_note')
+ const dataset = target.nodes[0].dataset
+ const is_attached = (form.find(`.upload-item[data-type='note'][data-id='${dataset.attachmentdata}']`)).length > 0
+ if(is_attached) {
+ (form.find(`.upload-item[data-type='note'][data-id='${dataset.attachmentdata}']`)).remove()
+ button.html(tr('attach'))
+ } else {
+ if(form.find(`.upload-item`).length + 1 > window.openvk.max_attachments) {
+ makeError(tr('too_many_attachments'), 'Red', 10000, 1)
+ return
+ }
+
+ button.html(tr('detach'))
+ form.find('.post-vertical').append(`
+
+
+
+
+
+
+ ${tr('note')}
+ ${ovk_proc_strtr(escapeHtml(dataset.name), 66)}
+
+
+
+
+
+ `)
+ }
+ })
+
+ __recieveNotes(0)
+})
+
+function showFastVideoUpload(node) {
+ let current_tab = 'file'
+ const msg = new CMessageBox({
+ title: tr('upload_video'),
+ close_on_buttons: false,
+ unique_name: 'video_uploader',
+ body: `
+
+ `,
+ buttons: [tr('close'), tr('upload_button')],
+ callbacks: [() => {msg.close()}, async () => {
+ const video_name = u(`#_fast_video_upload input[name='name']`).nodes[0].value
+ const video_desc = u(`#_fast_video_upload textarea[name='desc']`).nodes[0].value
+ let append_result = null
+
+ if(video_name.length < 1) {
+ u(`#_fast_video_upload input[name='name']`).nodes[0].focus()
+ return
+ }
+
+ const form_data = new FormData
+ switch(current_tab) {
+ default:
+ case 'file':
+ const video_file = u(`#_fast_video_upload input[name='blob']`).nodes[0]
+ if(video_file.files.length < 1) {
+ return
+ }
+
+ const video_blob = video_file.files[0]
+ form_data.append('ajax', '1')
+ form_data.append('name', video_name)
+ form_data.append('desc', video_desc)
+ form_data.append('blob', video_blob)
+ form_data.append('unlisted', 1)
+ form_data.append("hash", u("meta[name=csrf]").attr("value"))
+
+ window.messagebox_stack[1].getNode().find('.ovk-diag-action button').nodes[1].classList.add('lagged')
+ const fetcher = await fetch(`/videos/upload`, {
+ method: 'POST',
+ body: form_data
+ })
+ const fetcher_results = await fetcher.json()
+ append_result = fetcher_results
+
+ break
+ case 'youtube':
+ const video_url = u(`#_fast_video_upload input[name='link']`).nodes[0]
+ const video_link = video_url.value
+ if(video_link.length < 1) {
+ u(`#_fast_video_upload input[name='link']`).nodes[0].focus()
+ return
+ }
+
+ form_data.append('ajax', '1')
+ form_data.append('name', video_name)
+ form_data.append('desc', video_desc)
+ form_data.append('link', video_link)
+ form_data.append('unlisted', 1)
+ form_data.append("hash", u("meta[name=csrf]").attr("value"))
+
+ window.messagebox_stack[1].getNode().find('.ovk-diag-action button').nodes[1].classList.add('lagged')
+ const fetcher_yt = await fetch(`/videos/upload`, {
+ method: 'POST',
+ body: form_data
+ })
+ const fetcher_yt_results = await fetcher_yt.json()
+ append_result = fetcher_yt_results
+
+ break
+ }
+
+ if(append_result.payload) {
+ append_result = append_result.payload
+ const preview = append_result.image[0]
+ __appendToTextarea({
+ 'type': 'video',
+ 'preview': preview.url,
+ 'id': append_result.owner_id + '_' + append_result.id,
+ 'fullsize_preview': preview.url,
+ }, node)
+
+ window.messagebox_stack.forEach(msg_ => {
+ msg_.close()
+ })
+ } else {
+ fastError(append_result.flash.message)
+ msg.close()
+ }
+ }]
+ })
+
+ msg.getNode().find('.ovk-diag-body').attr('style', 'padding:0px;height: 161px;')
+ async function __switchTab(tab_name) {
+ current_tab = tab_name
+ u(`#_fast_video_upload .mb_tab`).attr('id', 'ki')
+ u(`#_fast_video_upload .mb_tab[data-name='${current_tab}']`).attr('id', 'active')
+
+ switch(current_tab) {
+ case 'file':
+ msg.getNode().find('#__content').html(`
+
+ `)
+ break
+ case 'youtube':
+ msg.getNode().find('#__content').html(`
+
+ `)
+ break
+ }
+ }
+
+ u('#_fast_video_upload').on('click', '.mb_tab', (e) => {
+ __switchTab(u(e.target).closest('.mb_tab').nodes[0].dataset.name)
+ })
+
+ u('#_fast_video_upload').on('change', '#blob', (e) => {
+ u('#_fast_video_upload #filename').html(escapeHtml(e.target.files[0].name))
+ u(`#_fast_video_upload input[name='name']`).nodes[0].value = escapeHtml(e.target.files[0].name)
+ })
+
+ __switchTab('file')
+}
+
+u(document).on('click', `.post-horizontal .upload-item .upload-delete`, (e) => {
+ e.preventDefault()
+ u(e.target).closest('.upload-item').remove()
+})
+
+u(document).on('click', `.vertical-attachment #small_remove_button`, (e) => {
+ e.preventDefault()
+ u(e.target).closest('.vertical-attachment').remove()
+})
+
+u(document).on('click', '.post-buttons .upload-item', (e) => {
+ e.preventDefault()
+ e.stopPropagation()
+})
+
+u(document).on('click', '.post.post-nsfw .post-content', (e) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ if(window.openvk.current_id == 0) {
+ return
+ }
+
+ u(e.target).closest('.post-nsfw').removeClass('post-nsfw')
+})
+
+u(document).on('focusin', '#write', (e) => {
+ const target = u(e.target).closest('#write')
+ target.find('.post-buttons').attr('style', 'display:block')
+ target.find('.small-textarea').addClass('expanded-textarea')
+})
+
+async function repost(id, repost_type = 'post') {
+ const repostsCount = u(`#repostsCount${id}`)
+ const previousVal = repostsCount.length > 0 ? Number(repostsCount.html()) : 0;
+
+ const msg = new CMessageBox({
+ title: tr('share'),
+ unique_name: 'repost_modal',
+ body: `
+
+ `,
+ buttons: [tr('send'), tr('cancel')],
+ callbacks: [
+ async () => {
+ const message = u('#repostMsgInput').nodes[0].value
+ const type = u(`input[name='repost_type']:checked`).nodes[0].value
+ let club_id = 0
+ try {
+ club_id = parseInt(u(`select[name='selected_repost_club']`).nodes[0].selectedOptions[0].value)
+ } catch(e) {}
+
+ const as_group = u(`input[name='asGroup']`).nodes[0].checked
+ const signed = u(`input[name='signed']`).nodes[0].checked
+ const attachments = u(`#repost_attachments`).nodes[0].value
+
+ const params = {}
+ switch(repost_type) {
+ case 'post':
+ params.object = `wall${id}`
+ break
+ case 'photo':
+ params.object = `photo${id}`
+ break
+ case 'video':
+ params.object = `video${id}`
+ break
+ }
+
+ params.message = message
+ if(type == 'group' && club_id != 0) {
+ params.group_id = club_id
+ }
+
+ if(as_group) {
+ params.as_group = Number(as_group)
+ }
+
+ if(signed) {
+ params.signed = Number(signed)
+ }
+
+ if(attachments != '') {
+ params.attachments = attachments
+ }
+
+ try {
+ res = await window.OVKAPI.call('wall.repost', params)
+
+ if(u('#reposts' + id).length > 0) {
+ if(repostsCount.length > 0) {
+ repostsCount.html(previousVal + 1)
+ } else {
+ u('#reposts' + id).nodes[0].insertAdjacentHTML('beforeend', `(1)`)
+ }
+ }
+
+ NewNotification(tr('information_-1'), tr('shared_succ'), null, () => {window.router.route(`/wall${res.pretty_id}`)});
+ } catch(e) {
+ console.error(e)
+ fastError(e.message)
+ }
+ },
+ Function.noop
+ ]
+ });
+
+ u('.ovk-diag-body').attr('style', 'padding: 14px;')
+ u('.ovk-diag-body').on('change', `input[name='repost_type']`, (e) => {
+ const value = e.target.value
+
+ switch(value) {
+ case 'wall':
+ u('#repost_signs').attr('style', 'display:none')
+ u(`select[name='selected_repost_club']`).attr('style', 'display:none')
+ break
+ case 'group':
+ u('#repost_signs').attr('style', 'display:flex')
+ u(`select[name='selected_repost_club']`).attr('style', 'display:block')
+ break
+ }
+ })
+
+ if(!window.openvk.writeableClubs) {
+ window.openvk.writeableClubs = await window.OVKAPI.call('groups.get', {'filter': 'admin', 'count': 100})
+ }
+
+ window.openvk.writeableClubs.items.forEach(club => {
+ u(`select[name='selected_repost_club']`).append(``)
+ })
+
+ if(window.openvk.writeableClubs.items.length < 1) {
+ u(`input[name='repost_type'][value='group']`).attr('disabled', 'disabled')
+ }
+}
+
+$(document).on("click", "#add_image", (e) => {
+ let isGroup = e.currentTarget.closest(".avatar_block").dataset.club != null
+ let group = isGroup ? e.currentTarget.closest(".avatar_block").dataset.club : 0
+
+ let body = `
+
+
${isGroup == true ? tr('groups_avatar') : tr('friends_avatar')}
+
${tr('formats_avatar')}
+
+
+
+
+
+
${tr('troubles_avatar')}
+
${tr('webcam_avatar')}
+
+ `
+
+ let msg = MessageBox(tr('uploading_new_image'), body, [
+ tr('cancel')
+ ], [
+ (function() {
+ u("#tmpPhDelF").remove();
+ }),
+ ]);
+
+ msg.attr("style", "width: 600px;");
+ document.querySelector(".ovk-diag-body").style.padding = "13px"
+
+ $("#avatarUpload input").on("change", (ev) => {
+ let image = URL.createObjectURL(ev.currentTarget.files[0])
+ $(".ovk-diag-body")[0].innerHTML = `
+ ${!isGroup ? tr("selected_area_user") : tr("selected_area_club")}
+
+ ${tr("selected_area_rotate")}
+
+
+
+
+
+
+
+
+ `
+
+ document.querySelector(".ovk-diag-action").insertAdjacentHTML("beforeend", `
+
+ `)
+
+ const image_div = document.getElementById('temp_uploadPic');
+ const cropper = new Cropper(image_div, {
+ aspectRatio: NaN,
+ zoomable: true,
+ minCropBoxWidth: 150,
+ minCropBoxHeight: 150,
+ dragMode: 'move',
+ background: false,
+ center: false,
+ guides: false,
+ modal: true,
+ viewMode: 2,
+ cropstart(event) {
+ document.querySelector(".cropper-container").classList.add("moving")
+ },
+ cropend(event) {
+ document.querySelector(".cropper-container").classList.remove("moving")
+ },
+ });
+
+ msg.attr("style", "width: 487px;");
+
+ document.querySelector("#_uploadImg").onclick = (evv) => {
+ cropper.getCroppedCanvas({
+ fillColor: '#fff',
+ imageSmoothingEnabled: false,
+ imageSmoothingQuality: 'high',
+ }).toBlob((blob) => {
+ document.querySelector("#_uploadImg").classList.add("lagged")
+ let formdata = new FormData()
+ formdata.append("blob", blob)
+ formdata.append("ajax", 1)
+ formdata.append("on_wall", Number(document.querySelector("#publish_on_wall").checked))
+ formdata.append("hash", u("meta[name=csrf]").attr("value"))
+
+ $.ajax({
+ type: "POST",
+ url: isGroup ? "/club" + group + "/al_avatar" : "/al_avatars",
+ data: formdata,
+ processData: false,
+ contentType: false,
+ error: (response) => {
+ fastError(response.flash.message)
+ },
+ success: (response) => {
+ document.querySelector("#_uploadImg").classList.remove("lagged")
+ u("body").removeClass("dimmed");
+ document.querySelector("html").style.overflowY = "scroll"
+ u(".ovk-diag-cont").remove();
+
+ if(!response.success) {
+ fastError(response.flash.message)
+ return
+ }
+
+ document.querySelector("#bigAvatar").src = response.url
+ document.querySelector("#bigAvatar").parentNode.href = "/photo" + response.new_photo
+
+ document.querySelector(".add_image_text").style.display = "none"
+ document.querySelector(".avatar_controls").style.display = "block"
+ }
+ })
+ })
+ }
+
+ $(".ovk-diag-body ._rotateLeft").on("click", (e) => {
+ cropper.rotate(90)
+ })
+
+ $(".ovk-diag-body ._rotateRight").on("click", (e) => {
+ cropper.rotate(-90)
+ })
+ })
+
+ $(".ovk-diag-body #_takeSelfie").on("click", (e) => {
+ $("#avatarUpload")[0].style.display = "none"
+
+ $(".ovk-diag-body")[0].insertAdjacentHTML("beforeend", `
+
+
+
+ `)
+
+ let video = document.querySelector("#_takeSelfieFrame video")
+
+ if(!navigator.mediaDevices) {
+ u("body").removeClass("dimmed");
+ document.querySelector("html").style.overflowY = "scroll"
+ u(".ovk-diag-cont").remove();
+
+ fastError(tr("your_browser_doesnt_support_webcam"))
+
+ return
+ }
+
+ navigator.mediaDevices
+ .getUserMedia({ video: true, audio: false })
+ .then((stream) => {
+ video.srcObject = stream;
+ video.play()
+
+ window._cameraStream = stream
+ })
+ .catch((err) => {
+ u("body").removeClass("dimmed");
+ document.querySelector("html").style.overflowY = "scroll"
+ u(".ovk-diag-cont").remove();
+
+ fastError(err)
+ });
+
+ function __closeConnection() {
+ window._cameraStream.getTracks().forEach(track => track.stop())
+ }
+
+ document.querySelector(".ovk-diag-action").insertAdjacentHTML("beforeend", `
+
+ `)
+
+ document.querySelector(".ovk-diag-action button").onclick = (evv) => {
+ __closeConnection()
+ }
+
+ document.querySelector("#_takeSnap").onclick = (evv) => {
+ let canvas = document.getElementById('_tempCanvas')
+ let context = canvas.getContext('2d')
+
+ canvas.setAttribute("width", video.clientWidth)
+ canvas.setAttribute("height", video.clientHeight)
+ context.drawImage(video, 0, 0, video.clientWidth, video.clientHeight);
+ canvas.toBlob((blob) => {
+ $("#_takeSnap").remove()
+
+ let file = new File([blob], "snapshot.jpg", {type: "image/jpeg", lastModified: new Date().getTime()})
+ let dt = new DataTransfer();
+ dt.items.add(file);
+
+ $("#_avaInput")[0].files = dt.files
+ $("#_avaInput").trigger("change")
+ $("#_takeSelfieFrame").remove()
+
+ __closeConnection()
+ })
+ }
+ })
+})
+
+$(document).on("click", ".avatarDelete", (e) => {
+ let isGroup = e.currentTarget.closest(".avatar_block").dataset.club != null
+ let group = isGroup ? e.currentTarget.closest(".avatar_block").dataset.club : 0
+
+ let body = `
+ ${tr("deleting_avatar_sure")}
+ `
+
+ let msg = MessageBox(tr('deleting_avatar'), body, [
+ tr('yes'),
+ tr('no')
+ ], [
+ (function() {
+ let formdata = new FormData()
+ formdata.append("hash", u("meta[name=csrf]").attr("value"))
+
+ $.ajax({
+ type: "POST",
+ url: isGroup ? "/club" + group + "/delete_avatar" : "/delete_avatar",
+ data: formdata,
+ processData: false,
+ contentType: false,
+ beforeSend: () => {
+ document.querySelector(".avatarDelete").classList.add("lagged")
+ },
+ error: (response) => {
+ fastError(response.flash.message)
+ },
+ success: (response) => {
+ if(!response.success) {
+ fastError(response.flash.message)
+ return
+ }
+
+ document.querySelector(".avatarDelete").classList.remove("lagged")
+
+ u("body").removeClass("dimmed");
+ document.querySelector("html").style.overflowY = "scroll"
+ u(".ovk-diag-cont").remove()
+
+ document.querySelector("#bigAvatar").src = response.url
+ document.querySelector("#bigAvatar").parentNode.href = response.new_photo ? ("/photo" + response.new_photo) : "javascript:void(0)"
+
+ if(!response.has_new_photo) {
+ document.querySelector(".avatar_controls").style.display = "none"
+ document.querySelector(".add_image_text").style.display = "block"
+ }
+ }
+ })
+ }),
+ (function() {
+ u("#tmpPhDelF").remove();
+ }),
+ ]);
+})
+
+async function __processPaginatorNextPage(page)
+{
+ const container = u('.scroll_container')
+ const container_node = '.scroll_node'
+ const parser = new DOMParser
+
+ const replace_url = new URL(location.href)
+ replace_url.searchParams.set('p', page)
+ /*replace_url.searchParams.set('al', 1)
+ replace_url.searchParams.set('hash', u("meta[name=csrf]").attr("value"))*/
+
+ const new_content = await fetch(replace_url.href)
+ const new_content_response = await new_content.text()
+ const parsed_content = parser.parseFromString(new_content_response, 'text/html')
+
+ const nodes = parsed_content.querySelectorAll(container_node)
+ nodes.forEach(node => {
+ const unique_id = node.dataset.uniqueid
+ if(unique_id) {
+ const elements_unique = u(`.scroll_node[data-uniqueid='${unique_id}']`).length
+ if(elements_unique > 0) {
+ console.info('AJAX | Found duplicates')
+ return
+ }
+ }
+
+ container.append(node)
+ })
+
+ u(`.paginator:not(.paginator-at-top)`).html(parsed_content.querySelector('.paginator:not(.paginator-at-top)').innerHTML)
+ if(u(`.paginator:not(.paginator-at-top)`).nodes[0].closest('.scroll_container')) {
+ container.nodes[0].append(u(`.paginator:not(.paginator-at-top)`).nodes[0].parentNode)
+ }
+
+ if(window.player && window.player.isAtAudiosPage() && window.player.isAtCurrentContextPage()) {
+ window.player.loadContext(page)
+ window.player.__highlightActiveTrack()
+ }
+
+ /*if(window.router) {
+ window.router.savePreviousPage()
+ }*/
+
+ const new_url = new URL(location.href)
+ new_url.hash = page
+ history.replaceState(null, null, new_url)
+
+ if(typeof __scrollHook != 'undefined') {
+ __scrollHook(page)
+ }
+}
+
+const showMoreObserver = new IntersectionObserver(entries => {
+ entries.forEach(async x => {
+ if(x.isIntersecting) {
+ if(Number(localStorage.getItem('ux.auto_scroll') ?? 1) == 0) {
+ return
+ }
+
+ if(u('.scroll_container').length < 1) {
+ return
+ }
+
+ /*if(window.player && window.player.isAtAudiosPage() && !window.player.isAtCurrentContextPage()) {
+ return
+ }*/
+
+ const target = u(x.target)
+ if(target.length < 1 || target.hasClass('paginator-at-top')) {
+ return
+ }
+
+ const current_url = new URL(location.href)
+ if(current_url.searchParams && !isNaN(parseInt(current_url.searchParams.get('p')))) {
+ return
+ }
+
+ target.addClass('lagged')
+ const active_tab = target.find('.active')
+ const next_page = u(active_tab.nodes[0] ? active_tab.nodes[0].nextElementSibling : null)
+ if(next_page.length < 1) {
+ u('.paginator:not(.paginator-at-top)').removeClass('lagged')
+ return
+ }
+
+ const page_number = Number(next_page.html())
+
+ try {
+ await __processPaginatorNextPage(page_number)
+ } catch(e) {
+ console.error(e)
+ }
+
+ bsdnHydrate()
+ u('.paginator:not(.paginator-at-top)').removeClass('lagged')
+ }
+ })
+}, {
+ root: null,
+ rootMargin: '0px',
+ threshold: 0,
+})
+
+if(u('.paginator:not(.paginator-at-top)').length > 0) {
+ showMoreObserver.observe(u('.paginator:not(.paginator-at-top)').nodes[0])
+}
+
+u(document).on('click', '#__sourceAttacher', (e) => {
+ MessageBox(tr('add_source'), `
+
+ ${tr('set_source_tip')}
+
+
+
+ `, [tr('cancel')], [
+ () => {Function.noop}
+ ])
+
+ __removeDialog = () => {
+ u("body").removeClass("dimmed");
+ document.querySelector("html").style.overflowY = "scroll"
+ u(".ovk-diag-cont").remove()
+ }
+
+ u('.ovk-diag-action').append(`
+
+ `)
+
+ u('.ovk-diag-action #__setsrcbutton').on('click', async (ev) => {
+ // Consts
+ const _u_target = u(e.target)
+ const nearest_textarea = _u_target.closest('#write')
+ const source_output = nearest_textarea.find(`input[name='source']`)
+ const source_input = u(`#source_flex_kunteynir input[type='text']`)
+ const source_value = source_input.nodes[0].value ?? ''
+ if(source_value.length < 1) {
+ return
+ }
+
+ ev.target.classList.add('lagged')
+
+ // Checking link
+ const __checkCopyrightLinkRes = await fetch(`/method/wall.checkCopyrightLink?auth_mechanism=roaming&link=${encodeURIComponent(source_value)}`)
+ const checkCopyrightLink = await __checkCopyrightLinkRes.json()
+
+ // todo переписать блять мессенджбоксы чтоб они классами были
+ if(checkCopyrightLink.error_code) {
+ __removeDialog()
+ switch(checkCopyrightLink.error_code) {
+ default:
+ case 3102:
+ fastError(tr('error_adding_source_regex'))
+ return
+ case 3103:
+ fastError(tr('error_adding_source_long'))
+ return
+ case 3104:
+ fastError(tr('error_adding_source_sus'))
+ return
+ }
+ }
+
+ // Making indicator
+ __removeDialog()
+ source_output.attr('value', source_value)
+ nearest_textarea.find('.post-source').html(`
+ ${tr('source')}: ${ovk_proc_strtr(source_value.escapeHtml(), 50)}
+
+ `)
+
+ nearest_textarea.find('.post-source #remove_source_button').on('click', () => {
+ nearest_textarea.find('.post-source').html('')
+ source_output.attr('value', 'none')
+ })
+ })
+
+ u('.ovk-diag-body').attr('style', `padding:8px;`)
+ u('.ovk-diag-cont').attr('style', 'width: 325px;')
+ u('#source_flex_kunteynir input').nodes[0].focus()
+})
+
+u(document).on('keyup', async (e) => {
+ if(u('#ovk-player-part .bsdn').length > 0) {
+ switch(e.keyCode) {
+ case 32:
+ u('#ovk-player-part .bsdn .bsdn_playButton').trigger('click')
+ break
+ case 39:
+ u('#ovk-player-part video').nodes[0].currentTime = u('#ovk-player-part video').nodes[0].currentTime + 2
+ break
+ case 37:
+ u('#ovk-player-part video').nodes[0].currentTime = u('#ovk-player-part video').nodes[0].currentTime - 2
+ break
+ }
+ }
+})
+
+u(document).on('mouseover mousemove mouseout', `div[data-tip='simple']`, (e) => {
+ if(e.target.dataset.allow_mousemove != '1' && e.type == 'mousemove') {
+ return
+ }
+
+ if(e.type == 'mouseout') {
+ u(`.tip_result`).remove()
+ return
+ }
+
+ const target = u(e.target).closest(`div[data-tip='simple']`)
+ const title = target.attr('data-title')
+ if(title == '') {
+ return
+ }
+
+ target.nodes[0].parentNode.insertAdjacentHTML('afterbegin', `
+
+ ${escapeHtml(title)}
+
+ `)
+})
+
+function setStatusEditorShown(shown) {
+ document.getElementById("status_editor").style.display = shown ? "block" : "none";
+}
+
+u(document).on('click', (event) => {
+ u('#ctx_menu').remove()
+ if(u('#status_editor').length < 1) {
+ return
+ }
+
+ if(!event.target.closest("#status_editor") && !event.target.closest("#page_status_text"))
+ setStatusEditorShown(false);
+})
+
+u(document).on('click', '#page_status_text', (e) => {
+ setStatusEditorShown(true)
+})
+
+async function changeStatus() {
+ const status = document.status_popup_form.status.value;
+ const broadcast = document.status_popup_form.broadcast.checked;
+
+ document.status_popup_form.submit.innerHTML = "";
+ document.status_popup_form.submit.disabled = true;
+
+ const formData = new FormData();
+ formData.append("status", status);
+ formData.append("broadcast", Number(broadcast));
+ formData.append("hash", document.status_popup_form.hash.value);
+ const response = await ky.post("/edit?act=status", {body: formData});
+
+ if(!parseAjaxResponse(await response.text())) {
+ document.status_popup_form.submit.innerHTML = tr("send");
+ document.status_popup_form.submit.disabled = false;
+ return;
+ }
+
+ if(document.status_popup_form.status.value === "") {
+ document.querySelector("#page_status_text").innerHTML = `[ ${tr("change_status")} ]`;
+ document.querySelector("#page_status_text").className = "edit_link page_status_edit_button";
+ } else {
+ document.querySelector("#page_status_text").innerHTML = status;
+ document.querySelector("#page_status_text").className = "page_status page_status_edit_button";
+ }
+
+ setStatusEditorShown(false);
+ document.status_popup_form.submit.innerHTML = tr("send");
+ document.status_popup_form.submit.disabled = false;
+}
+
+async function initGeo(tid) {
+ MessageBox(tr("attach_geotag"), "", ["Прикрепить", tr("cancel")], [(function () {
+ let marker = {
+ lat: currentMarker._latlng.lat,
+ lng: currentMarker._latlng.lng,
+ name: $(`#geo-name-input-${tid}`).val() ? $(`#geo-name-input-${tid}`).val() : $(`#geo-name-${tid}`).text()
+ };
+ $(`#post-buttons${tid} #geo`).val(JSON.stringify(marker));
+ $(`#post-buttons${tid} .post-has-geo`).text(`${tr("geotag")}: ${marker.name}`);
+ $(`#post-buttons${tid} .post-has-geo`).show();
+ }), Function.noop]);
+
+ const element = document.getElementById('osm-map');
+ element.style = 'height: 600px;';
+
+ let markerLayers = L.layerGroup();
+
+ let map = L.map(element, {
+ center: [55.322978, 38.673362],
+ zoom: 10,
+ attributionControl: false,
+ width: 800
+ });
+ let currentMarker = null;
+ markerLayers.addTo(map);
+
+ map.on('click', (e) => {
+ let lat = e.latlng.lat;
+ let lng = e.latlng.lng;
+
+ if (currentMarker) map.removeLayer(currentMarker);
+
+ $.get({
+ url: `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=jsonv2`,
+ success: (response) => {
+ markerLayers.clearLayers();
+
+ currentMarker = L.marker([lat, lng]).addTo(map);
+
+ let name = response?.name ?? response?.display_name ?? tr("geotag");
+ let content = `${name}`;
+ content += ``;
+
+ currentMarker.bindPopup(content).openPopup();
+ markerLayers.addLayer(currentMarker);
+ }
+ })
+ });
+
+ const geocoderControl = L.Control.geocoder({
+ defaultMarkGeocode: false,
+ }).addTo(map);
+
+ geocoderControl.on('markgeocode', function (e) {
+ console.log(e);
+ let lat = e.geocode.properties.lat;
+ let lng = e.geocode.properties.lon;
+ let name = (e.geocode.properties?.name ?? e.geocode.properties.display_name);
+
+ if (currentMarker) map.removeLayer(currentMarker);
+
+ currentMarker = L.marker([lat, lng]).addTo(map);
+ currentMarker.bindPopup(name).openPopup();
+
+ console.log(`${tr("latitude")}: ${lat}, ${tr("longitude")}: ${lng}`);
+ console.log(`${tr("name_of_the_place")}: ${name}`);
+
+ let marker = {
+ lat: lat,
+ lng: lng,
+ name: name
+ };
+ map.setView([lat, lng], 15);
+ });
+
+ L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
+ attribution: '© OpenStreetMap contributors'
+ }).addTo(map);
+
+ $(".ovk-diag-cont").width('50%');
+ setTimeout(function(){ map.invalidateSize()}, 100);
+}
+
+function openGeo(data, owner_id, virtual_id) {
+ MessageBox(tr("geotag"), "", [tr("nearest_posts"), "OK"], [(function () {
+ getNearPosts(owner_id, virtual_id);
+ }), Function.noop]);
+
+ let element = document.getElementById('osm-map');
+ element.style = 'height: 600px;';
+
+ let map = L.map(element, {attributionControl: false});
+ let target = L.latLng(data.lat, data.lng);
+ map.setView(target, 15);
+
+ let marker = L.marker(target).addTo(map);
+ marker.bindPopup(data.name ?? tr("geotag")).openPopup();
+
+ L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
+ attribution: '© OpenStreetMap contributors'
+ }).addTo(map);
+
+ $(".ovk-diag-cont").width('50%');
+ setTimeout(function(){ map.invalidateSize()}, 100);
+}
+
+function getNearPosts(owner_id, virtual_id) {
+ $.ajax({
+ type: "POST",
+ url: `/wall${owner_id}_${virtual_id}/nearest`,
+ success: (response) => {
+ if (response.success) {
+ openNearPosts(response);
+ } else {
+ MessageBox(tr("error"), `${tr("error_segmentation")}: ${(response?.error ?? "Unknown error")}`, ["OK"], [Function.noop]);
+ }
+ }
+ });
+}
+
+function getPostPopup(post) {
+ return `
+
+
+
+
+
+
+
+ |
+
+
+ ${post.owner.name}
+ ${post.owner.verified ? ` ` : ""}
+ ${post.owner.writes}
+
+
+ ${post.time}
+
+
+
+
+ ${post.preview}
+
+
+
+ ${tr("geotag")}: ${post.geo.name ?? tr("admin_open")}
+
+
+ |
+
+
+
+ `;
+}
+
+function openNearPosts(posts) {
+ if (posts.posts.length > 0) {
+ let MsgTxt = "";
+ MsgTxt += "
Показаны последние 25 постов за месяц";
+
+ MessageBox("Ближайшие посты", MsgTxt, ["OK"], [Function.noop]);
+
+ let element = document.getElementById('osm-map');
+ element.style = 'height: 600px;';
+
+ let markerLayers = L.layerGroup();
+ let map = L.map(element, {attributionControl: false});
+
+ markerLayers.addTo(map);
+
+ let markersBounds = [];
+ let coords = [];
+
+ posts.posts.forEach((post) => {
+ if (coords.includes(`${post.geo.lat} ${post.geo.lng}`)) {
+ markerLayers.getLayers().forEach((marker) => {
+ if (marker.getLatLng().lat === post.geo.lat && marker.getLatLng().lng === post.geo.lng) {
+ let content = marker.getPopup()._content += getPostPopup(post);
+ if (!content.startsWith(``))
+ content = `
${content}`;
+
+ marker.getPopup().setContent(content);
+ }
+ });
+ } else {
+ let marker = L.marker(L.latLng(post.geo.lat, post.geo.lng)).addTo(map);
+ marker.bindPopup(getPostPopup(post));
+ markerLayers.addLayer(marker);
+ markersBounds.push(marker.getLatLng());
+ }
+
+ coords.push(`${post.geo.lat} ${post.geo.lng}`);
+ })
+
+ let bounds = L.latLngBounds(markersBounds);
+ map.fitBounds(bounds);
+
+ L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
+ attribution: '©
OpenStreetMap contributors'
+ }).addTo(map);
+
+ $(".ovk-diag-cont").width('50%');
+ setTimeout(function () {
+ map.invalidateSize()
+ }, 100);
+ } else {
+ MessageBox("Ближайшие посты", "
Нет ближайших постов :(", ["OK"], [Function.noop]);
+ }
+}
diff --git a/install/sqls/00038-posts-geo.sql b/install/sqls/00051-posts-geo.sql
similarity index 100%
rename from install/sqls/00038-posts-geo.sql
rename to install/sqls/00051-posts-geo.sql