ImThatGuy / AvenoelExt

// ==UserScript==
// @name         AvenoelExt
// @author       ImThatGuy
// @description  Extension pour Avenoel
// @include      https://avenoel.org/*
// @require      https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
// @require      https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.8.0/jquery.modal.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js
// @require      https://jvcpremium.000webhostapp.com/files/remodal.min.js
// @require      https://raw.githubusercontent.com/avxto/nuContextMenu/master/src/jquery.nu-context-menu.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @grant        GM_getResourceText
// @grant        GM_getResourceURL
// @version      0.4
// @icon         https://i.imgur.com/JtPB5IO.png
// @copyright    2018+, ImThatGuy
// @license      MIT
// ==/UserScript==

/*
Avenoel extension. 2017-2018.
Developpé par ImThatGuy.

2018+, ImThatGuy.

Changelog
Version 0.1 : 1ère version.
Version 0.2 : Correction de bugs
              Ajout d'une notification dans l'onglet quand un nouveau msg est posté
			  Focus automatique du textarea après citation
Version 0.3 : Correction bouton actualiser depuis m.a.j avenoel
              Nouveau système pour ajouter un sticker perso
Version 0.4 : Correction ajout de stickers risibank / aperçu url
*/

/*jshint multistr: true */
(function() {
    'use strict';
    const version = '0.4';

	// CSS import
	$('head').append('<link rel="stylesheet" type="text/css" href="https://jvcpremium.000webhostapp.com/files/nu-context-menu.css"/>');
	$('head').append('<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>');
	$('head').append('<link rel="stylesheet" type="text/css" href="https://jvcpremium.000webhostapp.com/files/remodal.css"/>');
    $('head').append('<link rel="stylesheet" type="text/css" href="https://jvcpremium.000webhostapp.com/files/remodal-default-theme.css"/>');
	$('head').append('<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.css"/>');
	$('head').append('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pretty-checkbox@3.0/dist/pretty-checkbox.min.css"/>');
	$("head").append('<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">');

	// First time execute the script
	var firstTime = GM_getValue('firstTime');
	if (firstTime === undefined) {firstTime = true;}

	if (firstTime) { // Set all stored values
		GM_setValue("dragndrop", false);
		GM_setValue("refreshbtn", true);
		GM_setValue("tooltips", true);
		GM_setValue("notifs", true);
	}

	GM_setValue("firstTime", false);

	// OPTIONS
	var HEIGHT = "120";      // Hauteur du cadre en pixels
	var STICKERS_MAX = "60"; // Taille max des stickers en pixels
	//
	var dragNDrop = GM_getValue("dragndrop");
	var refreshBtn = GM_getValue("refreshbtn");
	var tooltips = GM_getValue("tooltips");
	var notifs = GM_getValue("notifs");

	// Variables

	var focusRisitas = true;

	var stickers = [
		'http://image.noelshack.com/fichiers/2016/46/1479639726-1467231909-1466015251-esp.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366197-risitas10.png',
		'http://image.noelshack.com/fichiers/2016/36/1473263674-jesus5.png',
		'http://image.noelshack.com/fichiers/2016/46/1479341443-issou.gif',
		'http://image.noelshack.com/fichiers/2016/30/1469971032-risitas246.png',
		'http://image.noelshack.com/fichiers/2016/26/1467335935-jesus1.png',
		'http://image.noelshack.com/fichiers/2016/38/1474488554-jesus18.png',
		'https://image.noelshack.com/fichiers/2017/21/1495823618-risitas596.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366209-risitas24.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541957-risitas198.png',
		'http://image.noelshack.com/fichiers/2016/38/1474490238-risitas440.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541952-risitas182.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366602-risitas94.png',
		'http://image.noelshack.com/fichiers/2017/14/1491484186-risitasueur.png',
		'http://image.noelshack.com/fichiers/2016/38/1474488637-jesus26.png',
		'http://image.noelshack.com/fichiers/2016/38/1474490303-risitas468.png',
		'http://image.noelshack.com/fichiers/2016/32/1470920801-jesus17.png',
		'http://image.noelshack.com/fichiers/2016/38/1474488564-jesus38.png',
		'http://image.noelshack.com/fichiers/2016/38/1474719470-risitas626.png',
		'http://image.noelshack.com/fichiers/2016/38/1474488632-jesus27.png',
		'http://image.noelshack.com/fichiers/2016/38/1474794851-risitas766.gif',
		'http://image.noelshack.com/fichiers/2016/30/1469541959-risitas206.png',
		'http://image.noelshack.com/fichiers/2016/38/1474488555-jesus24.png',
		'http://image.noelshack.com/minis/2016/30/1469561699-1466004337-reupload-3-2.png',
		'http://image.noelshack.com/fichiers/2016/47/1480064732-1467335935-jesus4.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366261-risitas51.png',
		'http://image.noelshack.com/fichiers/2016/32/1470920800-jesus14.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366648-risitas115.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366339-risitas39.png',
		'http://image.noelshack.com/fichiers/2016/46/1479465472-risitaspc.png',
		'http://image.noelshack.com/fichiers/2016/38/1474719464-risitas614.png',
		'http://image.noelshack.com/fichiers/2016/38/1474719465-risitas615.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541976-risitas216.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366188-risitas6.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366306-risitas52.png',
		'http://image.noelshack.com/fichiers/2016/30/1469971038-risitas258.png',
		'http://image.noelshack.com/fichiers/2016/38/1474490319-risitas575.png',
		'http://image.noelshack.com/fichiers/2016/38/1474797359-risitas770.gif',
		'http://image.noelshack.com/fichiers/2016/38/1474490319-risitas574.png',
		'http://image.noelshack.com/fichiers/2016/47/1479858878-1466366212-risitas32.png',
		'http://image.noelshack.com/fichiers/2016/38/1474719466-risitas617.png',
		'http://image.noelshack.com/fichiers/2016/38/1474719465-risitas616.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541968-risitas225.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541970-risitas226.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541968-risitas224.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541969-risitas227.png',
		'http://image.noelshack.com/fichiers/2016/30/1469541969-risitas228.png',
		'http://image.noelshack.com/fichiers/2016/38/1474488573-jesus49.png',
		'http://image.noelshack.com/fichiers/2016/46/1479465083-jesusetrsitas.png',
		'http://image.noelshack.com/fichiers/2016/38/1474490292-risitas493.png',
		'http://image.noelshack.com/fichiers/2016/38/1474488574-jesus50.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366203-risitas21.png',
		'http://image.noelshack.com/fichiers/2016/38/1474490239-risitas441.png',
		'http://image.noelshack.com/fichiers/2017/03/1484921410-1466366200-risitas13.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366296-risitas60.png',
		'http://image.noelshack.com/fichiers/2016/38/1474490330-risitas566.png',
		'http://image.noelshack.com/fichiers/2016/38/1474797331-risitas768.png',
		'http://image.noelshack.com/fichiers/2016/32/1470920814-jesus10.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366342-risitas59.png',
		'http://image.noelshack.com/fichiers/2016/24/1466366197-risitas11.png',
		'http://image.noelshack.com/fichiers/2016/38/1474490326-risitas582.png',
		'http://image.noelshack.com/fichiers/2016/26/1467309317-risitas157.png',
		'http://image.noelshack.com/fichiers/2016/38/1474755095-risitas719.png',
		'http://image.noelshack.com/fichiers/2016/50/1482027315-perplexe.png',
		'http://image.noelshack.com/fichiers/2016/50/1481985771-gendarmedeuxsucres.png',
		'http://image.noelshack.com/fichiers/2016/47/1480092147-1477945635-1465556572-elrisitassticker3-copy.png',
		'http://image.noelshack.com/fichiers/2016/48/1480373367-issddou.png',
		'http://image.noelshack.com/fichiers/2016/49/1481140349-jesus.png',
		'http://image.noelshack.com/fichiers/2016/49/1481140358-jesusdd2.png',
		'http://image.noelshack.com/fichiers/2016/41/1476374797-picsart-10-13-05-19-26.jpg',
		'http://image.noelshack.com/fichiers/2016/48/1480747401-picsart-12-03-07-36-33.jpg',
		'http://image.noelshack.com/fichiers/2016/48/1480747392-picsart-12-03-07-22-54.jpg',
		'http://image.noelshack.com/fichiers/2017/04/1485686507-risddb.png',
		'http://image.noelshack.com/fichiers/2017/02/1484127482-jesusah2.png',
		'http://image.noelshack.com/fichiers/2015/49/1448914032-elrisitasgif.gif',
		'http://image.noelshack.com/fichiers/2017/33/2/1502805310-jesus-hd-2.png'
	];

	var stickers_perso; // Stickers personnels
	try {
		stickers_perso = JSON.parse(GM_getValue("stickers-p-ave"));
	} catch (err) {
		stickers_perso = [];
	}

	var postContents = []; // All .post-content textarea

	// Functions

	function getTopicId() {
		var id = window.location.href.split("/")[4].split("-")[0];
		return id;
	}

	  // Notif
	var documentTitle = document.title;
	var lastmsg = "";
	var notifNb = 0;
	function notifCheck(id) {
		GM_xmlhttpRequest({
			method: "GET",
			url: "https://avenoel.org/api/v1/topics/"+id,
			headers: {
				"Content-Type": "application/x-www-form-urlencoded"
			},
			onload: function(response) {
				//console.log(response.responseText);
				var result = JSON.parse(response.responseText);
				//console.log(result);
				//alert(lastmsg);
				if (result.data.updated_at != lastmsg) {
					if (lastmsg !== "") {
						document.title = "("+notifNb+") " + documentTitle;
					}
					lastmsg = result.data.updated_at;
					notifNb += 1;
				}
			}
		});
	}

	  // Liste des sujets
	function listeSujets() {
		if ( $(".primary-page-title").length ) {
			return true;
		} else {
			return false;
		}

	}

      // Append last realtime
    function appendSticker(b) {
		$(".sticker-dernier").attr("src", b);
    }

	  // Define last sticker
	var dernierSticker;
	function defineDernierSticker() {
		dernierSticker = GM_getValue('dernierSticker');
	}
	defineDernierSticker();

	function getPostContent() {
		$('.post-content[name="content"]').each(function() {
			postContents.push( $(this) );
			//alert($(this));
		});
	}
	getPostContent();

	  // Add sticker
	function addSticker(sticker) {
		for (var i=0; i < postContents.length; i++) {
			var $textarea = postContents[i];
			var caretPos = $textarea[0].selectionStart;
			var textAreaTxt = $textarea.val();

			var txtToAdd = sticker + ' ';

			$textarea.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
			$textarea.focus();
		}
		// Last sticker
		GM_setValue('dernierSticker', sticker); // Défini le dernier sticker utilisé
		defineDernierSticker();
		if (dernierSticker !== undefined) {
			appendSticker(sticker);
		}
	}

	// Display stickers
	function displayStickers(stickers_list) {
		$(".stickers-i").empty();
		// Dernier sticker
		if (dernierSticker !== undefined) {
			$('.stickers-i').prepend('<img title="Dernier sticker utilisé" class="sticker-dernier" style="border:1px solid #9b9b9b;" src="'+dernierSticker+'">');
		}
		if (focusRisitas === false) {
			if (stickers_list.length <= 0) {
				$(".stickers-i").append("<i>Vous n'avez pas de stickers personnels.</i>");
			}
		}
		for (var i=0; i<stickers_list.length;i++)
		{
			if (focusRisitas === false) {
				$(".stickers-i").append('<img id="stickerperso" class="stickers-cadre" src="'+stickers_list[i]+'">');
			} else {
				$(".stickers-i").append('<img class="stickers-cadre" src="'+stickers_list[i]+'">');
			}
		}
		stickersListeners();
	}

	function addStickerToList(sticker) {
		stickers_perso.push(sticker);
		GM_setValue("stickers-p-ave", JSON.stringify(stickers_perso));
		location.reload();
	}

	function setOption(option) {
		if (GM_getValue(option) === true) {
			GM_setValue(option, false);
		} else {
			GM_setValue(option, true);
		}
	}

	function isChecked(option) {
		if (GM_getValue(option)) {
			return "checked";
		} else {
			return "";
		}
	}


	// Append
	  // Remodal
	$("body").append('<div class="remodal" data-remodal-id="modal">\
  <button data-remodal-action="close" class="remodal-close"></button>\
  <h1>AvenoelExt v'+version+' options</h1><hr>\
\
  <div class="pretty p-default"><input class="option-ave form-control" option="refreshbtn" type="checkbox" '+isChecked("refreshbtn")+'>\
  <div class="state"><label>Bouton actualiser</label></div></div><hr>\
\
  <div class="pretty p-default"><input class="option-ave form-control" option="dragndrop" type="checkbox" '+isChecked("dragndrop")+'>\
  <div class="state"><label>Drag and drop stickers</label></div></div><hr>\
\
  <div class="pretty p-default"><input class="option-ave form-control" option="tooltips" type="checkbox" '+isChecked("tooltips")+'>\
  <div class="state"><label>Tooltips</label></div></div><hr>\
\
  <div class="pretty p-default"><input class="option-ave form-control" option="notifs" type="checkbox" '+isChecked("notifs")+'>\
  <div class="state"><label>Notifications</label></div></div><hr>\
\
  <button data-remodal-action="confirm" class="remodal-confirm">OK</button>\
</div>');
	var inst = $('[data-remodal-id=modal]').remodal(); // Remodal init

	  // Main append
	$(".bbcodes").append('<span title="Options" class="glyphicon glyphicon-option-vertical options-i"></span> \
                         <span title="Ajouter un sticker personnel" class="glyphicon glyphicon-plus stickers-add"></span> \
						 <span title="Effacer ma liste de sticker personnels" class="glyphicon glyphicon-trash stickers-remove"></span> \
						 <span title="Changer de liste de stickers" class="glyphicon glyphicon-folder-open stickers-change"></span>\
						 <div id="drop-i">Déposer un sticker ici</div>\
                          <div class="stickers-i"></div>\
						 ');

	// Append boutons posts
	$(".message-actions").append('<li><span title="Ajouter un sticker personnel" class="glyphicon glyphicon-download add-sticker-p"></span></li>');


	displayStickers(stickers);

	// Focus msg quand citation
	$(".message-quote").click(function() {
		setTimeout(function() {
			var $textarea = postContents[postContents.length-1];
			//console.log($textarea);
			$textarea.focus();
		}, 200);
	});

	// Notif si nouveau msg est ajouté
	if (!listeSujets()) {
		if (notifs) {
			setInterval(function() {
				notifCheck(getTopicId());
			}, 2000);
		}
	}

	// Add refresh button
	if (!listeSujets()) {
		if (refreshBtn) {
			// Depuis update avenoel
			$(".grey-btn").each(function() {
				if ( $(this).html() == '<i class="glyphicon glyphicon-refresh"></i>' ) {
					$(this).remove();
				}
			});
			// Ajoute le btn
			$(".btn-primary").each(function() {
				if ( $(this).attr("href") == "https://avenoel.org/forum" ) {
					$('<a style="float:right" class="btn btn-primary" onclick="location.reload()">Actualiser</a>').insertAfter(this);
				}
			});
		}
	}

	// Drag n drop
	if (!dragNDrop) {
		setTimeout(function() {
			$("div#drop-i").remove();
		}, 10);
	}
	if (!listeSujets()) {
		if (dragNDrop) {
			$(".message-content img").draggable({
				//containment : '.topic-messages'
				revert : 'invalid',
				drag : function() {
					$("html, body").animate({ scrollTop: $(document).height() }, "slow");
					/*
					$('html, body').stop().animate({
						scrollTop: $("div#drop-i").offset().top
					}, 650);
					*/
				}
			});

			$('div#drop-i').droppable({

				accept : 'img',
				drop : function (e, ui) {
					addStickerToList(
						$(ui.draggable).attr("src")
					);
				}

			});
		}
	}

	$(".apercite-image").find("img").addClass("preview-del"); // Class pour delete aperçu url
	// Add sticker posts
	$("body").append('<div id="dialog"></div>');
	$(".add-sticker-p").click(function() {
		var b = $(this).parents().closest(".message-wrapper").find(".message-content").first().find("img");
		var permalink = $(this).parents().closest(".message-wrapper").find(".message-footer").first().find(".message-permalink").attr("href");
		//console.log(b);
		$("#dialog").empty();
		$("#dialog").append('<span style="font-size:12px;">Clique sur un sticker pour l\'ajouter à ta liste personnel</span><hr>');
		if (b.length > 0) {
			b.each(function() {
				if ($(this).attr("class") == "smiley" || $(this).attr("class") == "risi-fav-button" || $(this).attr("class") == "preview-del") {
					//$(this).remove();
				} else {
					$("#dialog").append('<img class="st-add-p" src="'+$(this).attr("src")+'">');
				}
			});
			$(".st-add-p").click(function() {
				addStickerToList($(this).attr("src"));
			});
		} else {
			$("#dialog").empty().append("Ce post ne contient aucun sticker.");
		}
		if ($("#dialog").find(".st-add-p").length <= 0) {
			$("#dialog").empty().append("Ce post ne contient aucun sticker.");
		}
		$("#dialog").dialog({
			title: "Sticker(s) du post "+permalink,
			width: 400,
			height: 250,
			modal: true,
			open: function(event, ui) {
				$(".ui-widget-overlay").click(function() {
					$("#dialog").dialog('close');
				});
			}
		});
	});

	// Listeners
	function stickersListeners() {
		$(".stickers-cadre, .sticker-dernier").click(function() {
			addSticker($(this).attr("src"));
		});
	}

	$(".stickers-change").click(function() {
		if (focusRisitas === true) {
			focusRisitas = false;
			displayStickers(stickers_perso);
		} else {
			focusRisitas = true;
			displayStickers(stickers);
		}
	});

	  // Options
	$(".options-i").click(function() {
		inst.open();
	});

	$(document).on('confirmation', '.remodal', function (e) {
		location.reload();
	});

	  // Delete stickers
	$(".stickers-remove").click(function() {
		if ( confirm("Etes-vous sûr de vouloir supprimer tous vos stickers personnels ?") ) {
			GM_setValue("stickers-p-ave", "[]");
			location.reload();
		}
	});

	  // Add sticker
	$(".stickers-add").click(function() {
		var b = prompt("Lien direct du sticker");
		if (b) {
			stickers_perso.push(b);
			GM_setValue("stickers-p-ave", JSON.stringify(stickers_perso));
			location.reload();
		}
	});

	  // Set option
	$(".option-ave").click(function() {
		setOption( $(this).attr("option") );
	});

	// Context menu
	$(function() {
		var context = $('body').nuContextMenu({

			hideAfterClick: true,

			items: '.stickers-cadre',

			callback: function(key, element) {
				if (key == "delete") {
					if ( $(element).attr("id") == "stickerperso" ) {
						$(element).remove();
						var stickerPersoDel = stickers_perso.indexOf($(element).attr("src"));
						if (stickerPersoDel > -1) {
							stickers_perso.splice(stickerPersoDel, 1);
						}
						GM_setValue("stickers-p-ave", JSON.stringify(stickers_perso));
						location.reload();
					} else {
						alert("Vous ne pouvez pas supprimer ce sticker");
					}
				} else if ( key == 'download' ) {
					var a = document.createElement('a');
					a.href = element.src;
					a.download = element.src;
					a.style.display = 'none';
					document.body.appendChild(a);
					a.click();
				} else if ( key == 'reply' ) {
					addSticker($(element).attr("src"));
				}
			},

			menu: [

				{
					name: 'download',
					title: 'Télécharger',
					icon: 'download',
				},

				{
					name: 'reply',
					title: 'Ajouter à mon post',
					icon: 'reply',
				},

				{
					name: 'void'
				},

				{
					name: 'delete',
					title: 'Supprimer',
					icon: 'trash',
				},
			]

		});

	});

	// Tooltips
	/*
	$('.sticker-dernier').qtip({
		content: {
			text: 'Dernier sticker utilisé'
		},
		style: {
			classes: 'qtip-light'
			//classes: 'qtip-tipsy'
		},
		position: {
			my: 'top left',
			at: 'bottom center'
		}
	});
	*/

	if (tooltips) {
		$('[title!=""]').qtip({
			style: {
				classes: 'qtip-light'
				//classes: 'qtip-tipsy'
			},
			position: {
				my: 'top left',
				at: 'bottom center'
			}
		});
	}

	// CSS
	GM_addStyle(".stickers-cadre, .sticker-dernier { max-height: "+STICKERS_MAX+"px; max-width: "+STICKERS_MAX+"px; opacity: 0.7; cursor: pointer; }\
				 .stickers-cadre:hover, .sticker-dernier:hover { opacity: 1 }\
                 .stickers-i { width: 100%; height: "+HEIGHT+"px; overflow: auto; }\
                 #drop-i { border-top : 1px solid #ccc; border-bottom : 1px solid #ccc; height : 40px; text-align: center; cursor: pointer }\
                 .stickers-change, .stickers-remove, .options-i, .stickers-add { cursor: pointer; float: right; margin-right: 15px; margin-top: 7px; }\
                 .add-sticker-p { cursor: pointer; color: #494949; font-size: 21px; vertical-align: middle; margin-left: 3px; }\
                 .st-add-p { cursor : pointer; max-height: 70px; max-width: 70px; margin-right: 5px; border-bottom: 2px solid #ccc; }\
                 .st-add-p:active { opacity: 0.7 }\
                 .st-add-p:hover { border-color: #494949; }\
");

})();