h41msh1c0r
Goto Top

Wordpress Notifications von Chateinträgen

Aloa in die Runde,

mal wieder was für mich Fachfremdes, gerichtet an die Webspezialisten:

Szenario:

- Blog erstellt
- Nutzer definiert / Accounts angelegt und Rechte auf das Nötigste beschränkt
- Chat plugin installiert (Anforderung an das Chatplugin waren: ohne extern Quellen auszukommen, simple as possible --> Chat Room)

Soweit alles i.O.

Jetzt wurde der Wunsch geäußert, sobald einer was schreibt das bei den anderen eine Notification ausgelöst wird.
Ich würde sowas ja direkt im Chatplugin verorten, das ist allerdings so simple das sowas dort nicht geht, zumindestens fand ich nichts in der Konfiguration.

Frage:
Kann man mit einem anderen Plugin(Notification Plugin) auf Ereignisse/Texteingaben im Chatplugin reagieren und dann eine Notification(Klick, Ton oder Popup) erzeugen?

Das was ich bisher an Notification Plugins gefunden habe, reagiert i.d.R. auf erscheinen von Einträgen, Kommentaren etc. aber das wars dann auch schon.

VG

Content-ID: 561062

Url: https://administrator.de/contentid/561062

Printed on: December 12, 2024 at 19:12 o'clock

143127
143127 Mar 27, 2020 updated at 15:31:06 (UTC)
Goto Top
Jetzt wurde der Wunsch geäußert, sobald einer was schreibt das bei den anderen eine Notification ausgelöst wird.
Mit etwas JavaScript müsste sich das direkt mit ein paar Änderungen am Quellcode des Plugins einrichten lassen, aber wir kennen ja dein ominöses
Chat plugin installiert
nicht face-smile.

var notification = new Notification("Neue Nachricht", {body : 'Ey, heute schon an ner Corona genippt?'});  
https://developer.mozilla.org/de/docs/Web/API/notification
H41mSh1C0R
H41mSh1C0R Mar 27, 2020 updated at 20:15:04 (UTC)
Goto Top
Hi vibrations,

das Plugin heißt "Chat Room" *gg*

Mal schauen ob ich am WE Zeit finde mich an diesem Nebenkriegsschauplatz zu tummeln.

Da gibts tatsache ein Git-Repo( WebDevStudios / Chat-Room ) zu. =)

VG und allen einen schönen Feierabend
colinardo
colinardo Mar 30, 2020 updated at 16:57:39 (UTC)
Goto Top
Servus @H41mSh1C0R ,
hab dir das mal schnell im Code des Plugins ergänzt, waren nur ein paar Zeilen und Arrays zu ergänzen.

Tausche den Inhalt sowohl des PHP-Files als auch des JavaScripts des Plugins durch den neuen Quellcode aus. Lade die Chat-Seite neu und freue dich über Browser-Benachrichtigungen face-wink.

Die Änderungen basieren auf der zur Zeit aktuellen Version des Plugins: Version: 0.1.3.
Bei Updates musst du natürlich aufpassen, denn dann ist die Anpassung wieder weg, am besten du legst mit dem Quellcode eine Kopie des Plugins an, dann sind die Änderungen geschützt, musst aber eventuelle Security-Updates des Plugins manuell pflegen.

back-to-topNeue /wp-content/plugins/chat-room/chat-room.php
<?php
/*
Plugin Name: Chat Room
Plugin URI: http://webdevstudios.com/support/wordpress-plugins/
Description: Chat Room for WordPress
Author: WebDevStudios.com
Version: 0.1.3
Author URI: http://webdevstudios.com/
License: GPLv2 or later
*/

/*
 Browser-Notification added by @colinardo (administrator.de)
*/

Class Chatroom {
	function __construct() {
		register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );  
		register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );  
		add_action( 'init', array( $this, 'register_post_types' ) );  
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );  
		add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );  
		add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );  
		add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );  
		add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );  
		add_filter( 'the_content', array( $this, 'the_content_filter' ) );  
	}

	function activation_hook() {
		$this->register_post_types();
		flush_rewrite_rules();
	}

	function deactivation_hook() {
		flush_rewrite_rules();
	}

	function register_post_types() {
		$labels = array(
			'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),  
			'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),  
			'add_new' => _x( 'Add New', 'book', 'chatroom' ),  
			'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),  
			'edit_item' => __( 'Edit Chat Room', 'chatroom' ),  
			'new_item' => __( 'New Chat Room', 'chatroom' ),  
			'all_items' => __( 'All Chat Rooms', 'chatroom' ),  
			'view_item' => __( 'View Chat Room', 'chatroom' ),  
			'search_items' => __( 'Search Chat Rooms', 'chatroom' ),  
			'not_found' => __( 'No Chat Rooms found', 'chatroom' ),  
			'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),  
			'parent_item_colon' => '',  
			'menu_name' => __( 'Chat Rooms', 'chatroom' )  
		);
		$args = array(
			'labels' => $labels,  
			'public' => true,  
			'publicly_queryable' => true,  
			'show_ui' => true,  
			'show_in_menu' => true,  
			'query_var' => true,  
			'capability_type' => 'post',  
			'has_archive' => true,  
			'hierarchical' => false,  
			'menu_position' => null,  
			'show_in_nav_menus' => true,  
			'supports' => array( 'title' )  
		);
		register_post_type( 'chat-room', $args );  
	}

	function enqueue_scripts() {
		global $post;
		if ( $post->post_type != 'chat-room' )  
			return;
		wp_enqueue_script( 'jquery' );  
		wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );  
		wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );  
	}
	function maybe_create_chatroom_log_file( $post_id, $post ) {
		if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )  
			return;
		$upload_dir = wp_upload_dir();
		$log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );  
		if ( file_exists( $log_filename ) )
			return;
		wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );  
		$handle = fopen( $log_filename, 'w' );  

		fwrite( $handle, json_encode( array() ) );

		// TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config 
	}
	function define_javascript_variables() {
		global $post;
		$current_user = wp_get_current_user();
		if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )  
			return; ?>
		<script>
		var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';  
		var chatroom_slug = '<?echo $post->post_name; ?>';  
		var wp_user_id = <?php echo $current_user->id;?>;
		</script>
		<?php

	}
	function ajax_check_updates_handler() {
		$upload_dir = wp_upload_dir();
		$log_filename = $this->get_log_filename( sanitize_text_field( $_POST['chatroom_slug'] ) );  
		$contents = $this->parse_messages_log_file( $log_filename );
		$messages = json_decode( $contents );
		foreach ( $messages as $key => $message ) {
			if ( $message->id <= $_POST['last_update_id'] )  
				unset( $messages[$key] );
		}
		$messages = array_values( $messages );
		echo json_encode( $messages );
		die;
	}

	/**
	 * AJAX server-side handler for sending a message.
	 *
	 * Stores the message in a recent messages file.
	 *
	 * Clears out cache of any messages older than 10 seconds.
	 */
	function ajax_send_message_handler() {
		$current_user = wp_get_current_user();
		$this->save_message( sanitize_text_field( $_POST['chatroom_slug'] ), $current_user->id, $_POST['message']);  
		die;
	}

	function save_message( $chatroom_slug, $user_id, $content) {
		$user = get_userdata( $user_id );

		if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {  
	    	// Set random color for each user
	    	$red = rand( 0, 16 );
	    	$green = 16 - $red;
	    	$blue = rand( 0, 16 );
		    $user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );  
	    	update_user_meta( $user_id, 'user_color', $user_text_color );  
	    }

		$content = esc_attr( $content );
		// Save the message in recent messages file

		$log_filename = $this->get_log_filename( $chatroom_slug );
		$contents = $this->parse_messages_log_file( $log_filename );
		$messages = json_decode( $contents );
		$last_message_id = 0; // Helps determine the new message's ID 
		foreach ( $messages as $key => $message ) {
			if ( time() - $message->time > 10 ) {
				$last_message_id = $message->id;
				unset( $messages[$key] );
			}
			else {
				break;
			}
		}
		$messages = array_values( $messages );
		if ( ! empty( $messages ) )
			$last_message_id = end( $messages )->id;
		$new_message_id = $last_message_id + 1;
		$messages = array(
			'id' => $new_message_id,  
			'time' => time(),  
			'sender' => $user_id,  
			'sendername' => $user->user_login,  
			'senderfullname' => $user->first_name . ' ' . $user->last_name,  
			'contents' => $content,  
			'html' => '<div class="chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',  
		);
		$this->write_log_file( $log_filename, json_encode( $messages ) );

		// Save the message in the daily log
		$log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );  
		$contents = $this->parse_messages_log_file( $log_filename );
		$messages = json_decode( $contents );
		$messages = array(
			'id' => $new_message_id,  
			'time' => time(),  
			'sender' => $user_id,  
			'sendername' => $user->user_login,  
			'senderfullname' => $user->first_name . ' ' . $user->last_name,  
			'contents' => $content,  
			'html' => '<div class="chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',  
		);
		$this->write_log_file( $log_filename, json_encode( $messages ) );
	}
	function write_log_file( $log_filename, $content ) {
		$handle = fopen( $log_filename, 'w' );  
		fwrite( $handle, $content );
	}



	function get_log_filename( $chatroom_slug, $date = 'recent' ) {  
		$upload_dir = wp_upload_dir();
		$log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;  
		return $log_filename;
	}

	function parse_messages_log_file( $log_filename ) {
		$upload_dir = wp_upload_dir();
		$handle = fopen( $log_filename, 'r' );  
		$contents = fread( $handle, filesize( $log_filename ) );
		fclose( $handle );
		return $contents;
	}

	function the_content_filter( $content ) {
		global $post;
		if ( $post->post_type != 'chat-room' )  
			return $content;
		if ( ! is_user_logged_in() )  {
			?>You need to be logged in to participate in the chatroom.<?php
			return;
		}

		?>
		<div class="chat-container">  
		</div>
		<textarea class="chat-text-entry"></textarea>  
		<?php
		return '';  
	}

}

$chatroom = new Chatroom();

back-to-topNeue /wp-content/plugins/chat-room/chat-room.js

var last_update_received = 0;
var first_update = true;

function chatroom_check_updates() {
	jQuery.post(
		ajaxurl,
		{
			action: 'check_updates',  
			chatroom_slug: chatroom_slug,
			last_update_id: last_update_id
		},
		function (response) {
			chats = jQuery.parseJSON( response );
			if ( chats !== null ) {
				for ( i = 0; i < chats.length; i++ ) {
					if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )  
						continue;
					jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );  
					if (wp_user_id != chats[i].sender && ! first_update){
						var notification = new Notification(
							'Nachricht von ' + chats[i].senderfullname + ' (' + chats[i].sendername + ')',  
							{body : chats[i].contents}
						);
					}
					last_update_id = chats[i].id;
					jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container').scrollHeight - jQuery('div.chat-container').height() }, 100);  
				}
			}
			first_update = false;
		}
	);
	setTimeout( "chatroom_check_updates()", 1000 );  
}

function chatroom_strip_slashes(str) {
    return (str + '').replace(/\\(.?)/g, function (s, n1) {  
        switch (n1) {
        case '\\':  
            return '\\';  
        case '0':  
            return '\u0000';  
        case '':  
            return '';  
        default:
            return n1;
        }
    });
}

jQuery(document).ready( function() {
	last_update_id = 0;
	get_notification_permission();
	chatroom_check_updates();
	jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {  
		if ( event.charCode == 13 || event.keyCode == 13 ) {
			chatroom_send_message();
			return false;
		}
	});
});

function chatroom_send_message() {
	message = jQuery( 'textarea.chat-text-entry' ).val();  
	jQuery( 'textarea.chat-text-entry' ).val('');  
	jQuery.post(
		ajaxurl,
		{
			action: 'send_message',  
			chatroom_slug: chatroom_slug,
			message: message
		},
		function (response) {
		}
	);

}

function get_notification_permission(){
	// Let's check if the browser supports notifications 
  if (!("Notification" in window)) {  
    return false;
  }else if (Notification.permission === "granted") {  
    // If it's okay let's create a notification 
	return true
  }else if (Notification.permission !== 'denied') {  
	Notification.requestPermission(function (permission) {});
	return false;
  }
}

Code hat nur einen Basis-Test durchlaufen, nicht mehr nicht weniger, kost dich dafür nüscht face-wink .Wie immer alles ohne Gewähr face-smile.

Grüße Uwe
H41mSh1C0R
H41mSh1C0R Mar 31, 2020 at 22:34:26 (UTC)
Goto Top
Mensch Uwe,

das wandert gleich nach dem Morgen Tee in 7h auf die Prio0 des Tages.

*g*

Fettes Danke und gn8/gmorgen und Naja einen schönen 1.April