Advertisement
Tlams

JASS_Connector

Oct 22nd, 2013
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.92 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #Script basé sur les logs
  4.  
  5. import time
  6. import ConfigParser
  7. import socket
  8. import hashlib
  9. import threading
  10. import encodings
  11. from sys import exit
  12. import tail as tailer
  13. import re
  14.  
  15. ####
  16.  
  17. def __unicode__(self): #Permet les caractéres spéciaux type FR // précéder le message par u // print u"xxx"
  18.     return unicode(self.name)
  19.  
  20. def strReplace(str, array): #Permet de remplacer des caractéres par d'autres
  21.     for search, replace in array:
  22.         str = str.replace(search, replace)
  23.     return str
  24.  
  25. def send2peers(name, message):
  26.     PEERS_COUNT = int(0)  
  27.     while PEERS_COUNT != len(LIST_SERVER.split(',')): # Envoi à tous les peers
  28.         PEER = LIST_SERVER.split(',')[PEERS_COUNT]
  29.         PORT_PEER = PEER.split(':')[1]
  30.         IP_PEER = PEER.split(':')[0]
  31.         sock.sendto(USERNAME + "|-|" + hashlib.sha256(PASSWORD).hexdigest() + "|-|" + TAG + "|-|" + str(name) + "|-|" + str(message), (IP_PEER, int(PORT_PEER)))
  32.         PEERS_COUNT = PEERS_COUNT + 1
  33.  
  34. def getplayerlist():
  35.     global getinfomarkeur
  36.     PEERS_COUNT = int(0)  
  37.     while PEERS_COUNT != len(LIST_SERVER.split(',')): # Envoi à tous les peers
  38.         time.sleep(0.5)
  39.         getinfomarkeur = 1
  40.         PEER = LIST_SERVER.split(',')[PEERS_COUNT]
  41.         PORT_PEER = PEER.split(':')[1]
  42.         IP_PEER = PEER.split(':')[0]
  43.         sock.sendto("\xFF\xFF\xFF\xFFgetstatus", (IP_PEER, int(PORT_PEER))) # commande
  44.         PEERS_COUNT = PEERS_COUNT + 1
  45.  
  46. ###
  47.  
  48. #LECTURE LOCAL LOG
  49. class thread_send(threading.Thread):    
  50.     def __init__(self, nom=''):
  51.         threading.Thread.__init__(self)
  52.         self.nom = nom
  53.         self.Terminated = False
  54.        
  55.     def run(self):
  56.         new_back = "none"
  57.         new_player = int(0)
  58.         player_tab = [-1,-1,-1,-1,-1,
  59.                       -1,-1,-1,-1,-1,
  60.                       -1,-1,-1,-1,-1,
  61.                       -1,-1,-1,-1,-1,
  62.                       -1,-1,-1,-1,-1,
  63.                       -1,-1,-1,-1,-1,
  64.                       -1,-1,-1,-1] #INIT tableau 32places de correspondance payers id / names
  65.        
  66.         for new in tailer.follow(open(JKA_LOG_FILE)):
  67.             if ((new != new_back) and (new != "")):
  68.                 try:
  69.                     """
  70.                    if((players_flag[4]) in new): #Détection du !playerlist pour la liste des joueurs
  71.                        getplayerlist()
  72.                    """    
  73.                     if ((message_flag[0]) in new): #Détection d'un message
  74.                         #Traitement de la chaine new
  75.                         message = strReplace(new, replace_flag_chat).split('||')[2] #Remplacement des flag puis recup message
  76.                         #message = strReplace(message, replace_color_flag)  #on vire les color_flag
  77.                         name = strReplace(new, replace_flag_chat).split('||')[1]  #Remplacement des flag puis recup id + player
  78.                         name = name[3:] # on dégage l'id inutile
  79.                         #name = strReplace(name, replace_color_flag)  #on vire les color_flag
  80.                         if (message[:5] != "_team"):       #Detection du say team (continuer si non)
  81.                             send2peers(name, message)
  82.                            
  83.                     elif((players_flag[1]) in new): #Détection d'une connexion
  84.                         id_newplayer = new[-13:-10] #On chope juste l'id
  85.                         id_newplayer = int(strReplace(id_newplayer,replace_flag_players)) #convertion str en int + dégage espace autour
  86.                         #print "newplayerID=",id_newplayer
  87.                         new_player = 1 #On signale la présence d'une nouvelle connexion pour la ligne suivante !!
  88.                        
  89.                     elif (new_player == 1): #Détection nom nouveau player via la précédante lecture
  90.                         new_player = 0 #On RAZ la variable
  91.                         name_newplayer = new[8:] #On chope juste le nom
  92.                         name_newplayer = name_newplayer[:-1] #On jecte le dernier " à la con  
  93.                         player_tab[id_newplayer] = name_newplayer #Ajout dans liste
  94.                         #print player_tab
  95.                         message = PLAYER_CO +" "+ USERNAME + "!"
  96.                         send2peers(name_newplayer, message) #On indique à tous sa présence !!!
  97.  
  98.                     elif((players_flag[0]) in new): #Détection d'une déconnexion
  99.                         id_newplayer = new[-15:-12] #On chope juste l'id
  100.                         #print id_newplayer
  101.                         player_tab[int(id_newplayer)] = -1 #Zoouup!
  102.                         #print player_tab
  103.                         message = PLAYER_DISCO +" "+ USERNAME + "!"
  104.                         send2peers(name_newplayer, message) #On indique à tous sa présence !!!
  105.                        
  106.              
  107.                 except:
  108.                     print "An error has occurred while processing!"
  109.                 new_back = new
  110.  
  111.            
  112.     def stop(self):
  113.         self.Terminated = True
  114.  
  115. #RECEPTION
  116. class thread_recept(threading.Thread):    
  117.     def __init__(self, nom=''):
  118.         threading.Thread.__init__(self)
  119.         self.nom = nom
  120.         self.Terminated = False
  121.        
  122.     def run(self):
  123.         global getinfomarkeur
  124.         getinfomarkeur = 0
  125.         while True:
  126.             #try:
  127.             data, addr = sock_recu.recvfrom(20000)
  128.             if addr[0] in AUTORISE_IPS_LIST:
  129.                 if(getinfomarkeur == 1): # PROBL7ME DE MARKEUR
  130.                     players = re.findall(r'"(.*?)(?<!\\)"', strReplace(data, replace_color_flag))
  131.                     print data
  132.                     sock.sendto("\xFF\xFF\xFF\xFFrcon " + JKA_RCON + " say ^3List of players on " + addr[0] + "(" + str(addr[1]) + ")" + ":^7" +  ', '.join(players), (JKA_IP, int(JKA_PORT)))  
  133.                     getinfomarkeur = 0
  134.                 else:
  135.                     DATE = int(time.time())
  136.                     SERVERNAME_recv = data.split('|-|')[0]
  137.                     PASSWORD_recv = data.split('|-|')[1]
  138.                     TAG_recv = data.split('|-|')[2]
  139.                     NAME_recv = data.split('|-|')[3]
  140.                     MESSAGE_recv = data.split('|-|')[4]
  141.                     if (hashlib.sha256(PASSWORD).hexdigest() == PASSWORD_recv):
  142.                         print u"Received data[",SERVERNAME_recv,"]",NAME_recv,":",MESSAGE_recv
  143.                         sock.sendto("\xFF\xFF\xFF\xFFrcon " + JKA_RCON + " svsay ^2[^7" + SERVERNAME_recv + "^2]" +  "^2[^7" + NAME_recv + "^2]:" + MESSAGE_recv, (JKA_IP, int(JKA_PORT)))  
  144.                     else:
  145.                         print u"Incorrect password[",SERVERNAME_recv,"]"
  146.             else:
  147.                 print u"Unauthorized IP!"
  148.             #except:
  149.              #   print u"An error occurred while receiving or processing packet"
  150.     def stop(self):
  151.         self.Terminated = True
  152.  
  153.  
  154.  
  155. print "------------------------"
  156. print "-- Programme de Tlams"
  157. print "-- Version 1.0"
  158. print "-- Date: 28/09/13"
  159. print "-- Langage: Python V2.7"
  160. print u"-- Email: tlams[at]free.fr"
  161. print u"-- Fonction: Script de chat inter-serveur JKA / JASS MOD"
  162. print "------------------------"
  163. print ""
  164.  
  165. time.sleep(1)
  166.  
  167. #LECTURE DU FICHIER DE CONFIGURATION    
  168. print "Opening configurations file...",
  169. try:
  170.     config = ConfigParser.RawConfigParser()
  171.     config.read('config.ini')
  172.     print "[OK]"
  173. except:
  174.     print "[FAILED]"
  175.     print u"Opening the configuration file (config.ini) failed!"
  176.     print "File not available."
  177.     print "Closing..."
  178.     time.sleep(5)
  179.     exit(0)
  180.  
  181. time.sleep(1)
  182.  
  183. #SCRIPT INFO
  184. TAG = "JASS_JKA"
  185.  
  186. #TRAITEMENT DU FICHIER DE CONFIG
  187. print u"Reading the configuration file..."
  188. try:
  189.     JKA_LOG_FILE = config.get('JKA', 'logfile')
  190.     print u"[Info-config]LogFile:",JKA_LOG_FILE
  191.     JKA_RCON = config.get('JKA', 'RCON')
  192.     JKA_IP = config.get('JKA', 'IP_server')
  193.     print u"[Info-config]JKA-ServeurIP:",JKA_IP
  194.     JKA_PORT = config.get('JKA', 'PORT_server')
  195.     print u"[Info-config]JKA-ServeurPORT:",JKA_PORT
  196.     LOCAL_IP = config.get('LOCAL', 'IP')
  197.     print u"[Info-config]Script IP:",LOCAL_IP
  198.     LOCAL_PORT = config.get('LOCAL', 'PORT')
  199.     print u"[Info-config]Script PORT:",LOCAL_PORT
  200.     USERNAME = config.get('LOCAL', 'Username')
  201.     print u"[Info-config]Serveur nom:",USERNAME
  202.     PASSWORD = config.get('LOCAL', 'Password')
  203.     LIST_SERVER = config.get('PEERS', 'List_servers')
  204.     print u"[Info-config]Liste PEERS:",LIST_SERVER
  205.     AUTORISE_IPS = config.get('PEERS', 'IP_Autorise')
  206.     print u"[Info-config]IP autorisés:",AUTORISE_IPS
  207.     PLAYER_CO = config.get('LANG', 'player_co')
  208.     PLAYER_DISCO = config.get('LANG', 'player_disco')
  209. except:
  210.     print "[FAILED]"
  211.     print "File is corrupt or data are invalid !"
  212.     print "Closing..."
  213.     time.sleep(5)
  214.     exit(0)
  215.  
  216. print ""
  217. time.sleep(1)
  218.  
  219. # CREATION DU TABLEAU IP AUTORISES
  220. AUTORISE_IPS_LIST = []
  221. nb_ips = int(0)
  222.  
  223. while nb_ips != len(AUTORISE_IPS.split(',')):
  224.     AUTORISE_IPS_LIST.append(AUTORISE_IPS.split(',')[nb_ips])
  225.     nb_ips = nb_ips + 1
  226.  
  227.  
  228. #PREPARATION SOCKET UDP
  229. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  230. sock_recu = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  231.  
  232.  
  233. #CREATION DU SOCK LOCAL
  234. print "Opening a local sock...",
  235. try:
  236.     sock_recu.bind((LOCAL_IP, int(LOCAL_PORT)))
  237.     print "[OK]"
  238. except:  
  239.     print "[FAILED]"
  240.     print u"A socket is already open on this port!"
  241.     print "Closing..."
  242.     time.sleep(5)
  243.     exit(0)  
  244.  
  245. #JKA FLAG
  246. message_flag = [': say']
  247. players_flag = ['disconnected','connected:',' Name: ','Client','!playerlist']
  248. replace_flag_players = [(' ', '')]
  249. replace_flag_chat = [(': Cmd', '||'), (': say', '||')]
  250. replace_color_flag = [('^0', ''), ('^1', ''), ('^2', ''), ('^3', ''), ('^4', ''), ('^5', ''), ('^6', ''), ('^7', ''), ('^8', '')]
  251.  
  252.  
  253. #START THREAD
  254.        
  255. a = thread_send('envoi_donne')
  256. a.start()
  257.  
  258. b = thread_recept('recept_donne')
  259. b.start()
  260.  
  261.  
  262. print u"Loading completed !"
  263. print ""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement