viewgit/index.php:465 Only variables should be passed by reference [2048]

viewgit/index.php:466 Non-static method GeSHi::get_language_name_from_extension() should not be called statically [2048]

  1. # -*- coding: utf-8 -*-
  2. #
  3. # mlmanager is a python package that aims to "organize"
  4. # your mldonkey downloads.
  5. #
  6. # You can easily write a script that take care of moving
  7. # a file in the right place and to write emails to the right
  8. # people that need to know about the download.
  9. #
  10. #
  11. # It is released under the GNU General Public License Version 3
  12. #
  13. # Author: Leonardo Robol <leo@robol.it>
  14.  
  15.  
  16. #
  17. # START OF CONFIGURATION SECTION
  18. #
  19.  
  20. # The fully qualified (or not fully qualified - it really doesn't matter)
  21. # domain that the server is part of.
  22. domain = "robol.it"
  23.  
  24. # This is the mail address that will be set as sender for all
  25. # the emails generated by the script.
  26. from_addr = "mldonkey <mldonkey@%s>" % domain
  27.  
  28. # Mail server that the script will use to deliver emails. It must be properly
  29. # configured to relay mail from the domain selected.
  30. mail_server = "localhost"
  31.  
  32. # Users that should be notified when an error occurs in the script. You
  33. # can use the wildcard "owner" to match the owner of the file downladed.
  34. # This is generally true for every email function in mlmanager
  35. error_recipients = [ "owner" ]
  36.  
  37. # Number of times that rsync should try to transfer the file before
  38. # giving up.
  39. rsync_tries = 5
  40.  
  41. # Directory in which files are stored.
  42. files_incoming = "/removable/data/mldonkey/incoming/files"
  43.  
  44. # Set file extensions to match. You can add extensions in every category
  45. video_extensions = ['avi', 'mpeg', 'mpg', 'mkv', 'm2v', 'divx', 'xvid']
  46. audio_extensions = ['mp3', 'ogg', 'wav', 'flac', 'aac' ]
  47. text_extensions = ['pdf', 'doc', 'odt', 'ods', 'odp', 'ppt', 'rtf',
  48. 'pps', 'xls' , 'txt' ]
  49. cdimage_extensions = [ 'iso', 'nrg' ]
  50. archive_extensions = [ 'rar', 'zip', '7z', 'tar.gz', 'tar.bz2', 'lzo' ]
  51.  
  52.  
  53. #
  54. # END OF CONFIGURATION
  55. #
  56. #
  57. # START OF CODE
  58. #
  59.  
  60. __author__ = "Leonardo Robol <leo@robol.it>"
  61.  
  62. import os, sys, socket, shutil, subprocess, time, smtplib
  63. from email.mime.text import MIMEText
  64.  
  65. class FileType():
  66. """
  67. This class represent the type of a file, i.e you
  68. can check if it is a video, a text, an image...
  69. It can be:
  70. - video
  71. - audio
  72. - text
  73. - archive
  74. - other
  75. """
  76.  
  77. def __init__(self, filename):
  78. self._filename = filename
  79. self._detect_type ()
  80.  
  81.  
  82. def _test_extension(self, extension):
  83. return self._filename.lower().endswith(extension)
  84.  
  85. def _detect_type(self):
  86. """Detect the type of the file and save it in the internal
  87. varaible _type"""
  88. if len(filter(self._test_extension, video_extensions)) > 0:
  89. self._type = "video"
  90. elif len(filter(self._test_extension, audio_extensions)) > 0:
  91. self._type = "audio"
  92. elif len(filter(self._test_extension, text_extensions)) > 0:
  93. self._type = "text"
  94. elif len(filter(self._test_extension, cdimage_extensions)) > 0:
  95. self._type = "cdimage"
  96. elif len(filter(self._test_extension, archive_extensions)) > 0:
  97. self._type = "archive"
  98. else:
  99. self._type = "other"
  100.  
  101. def is_video(self):
  102. return (self._type == "video")
  103.  
  104. def is_image(self):
  105. return (self._type == "audio")
  106.  
  107. def is_text(self):
  108. return (self._type == "text")
  109.  
  110. def is_cdimage(self):
  111. return (self._type == "cdimage")
  112.  
  113. def is_archive(self):
  114. return (self._type == "archive")
  115.  
  116. def __str__(self):
  117. return self._type
  118.  
  119. def __repr__(self):
  120. return "<FileType '%s'>" % self._type
  121.  
  122.  
  123. class Download():
  124. """
  125. This class represent a file or a folder downloaded via mldonkey.
  126. You should create an instance of this calling
  127.  
  128. d = Download()
  129.  
  130. or, if you want
  131.  
  132. d = Download(username = "admin", password = "mysecretpassword")
  133.  
  134. This allow the script to connect to the mldonkey daemon and ensure
  135. that the file have been committed. It is not needed for mldonkey
  136. >= 2.7, but IT IS REQUIRED if you run an earlier mldonkey!
  137. """
  138.  
  139. def __init__(self, username = None, password = None, filename = None, group = None):
  140. """Perform some heuristic to determine the filetype,
  141. filename, groups and similar"""
  142.  
  143. # Set username and password
  144. self._username = username
  145. self._password = password
  146.  
  147. # If you do not provide username or password we can't
  148. # execute any command
  149. if not self._username or not self._password:
  150. self._authentication_available = False
  151.  
  152. self._filename = filename
  153. self._group = group
  154.  
  155. # If filename is not set then we can recover it
  156. # from the environment variables.
  157. if self._filename is None:
  158. self._filename = os.getenv("FILENAME")
  159.  
  160. # La durata del download in secondi
  161. self._duration = os.getenv("DURATION")
  162.  
  163. # Recover other data from environment
  164. if not self._group:
  165. self._group = os.getenv("FILE_GROUP")
  166.  
  167. self._owner = os.getenv("FILE_OWNER")
  168. self._incoming = files_incoming
  169.  
  170. self._user_email = os.getenv("USER_EMAIL")
  171.  
  172. # The file is not yet committed. You will need to commit it
  173. # before trying to move it. If we do not have authentication
  174. # assume that auto commit is enabled
  175. self._committed = False
  176. if not self._authentication_available:
  177. self._committed = True
  178.  
  179. # Construct the path of the file; this will be the real
  180. # path after it will be committed!
  181. self._dest_path = self._incoming
  182. if not self._dest_path.endswith(os.path.sep):
  183. self._dest_path += os.path.sep
  184. self._dest_path += self._filename
  185.  
  186. try:
  187. self._type = FileType(self._filename)
  188. except Exception, e:
  189. self._type = "other"
  190.  
  191.  
  192. def __repr__(self):
  193. return "<Download '%s'>" % self._filename
  194.  
  195. def _authentication_command (self):
  196. if not self._authentication_available:
  197. self._notify_error("Authentication data is not available, I can't authenticate to mldonkey")
  198. return None
  199. return "auth %s %s" % (self._username, self._password)
  200.  
  201. def commit(self):
  202. """Commit the file, i.e. save it to the hard disk
  203. in its final position. This should be the first
  204. thing you do"""
  205.  
  206. authentication = self._authentication_command ()
  207. if not authentication:
  208. return None
  209.  
  210. commands = [ authentication,
  211. "commit" ]
  212. self.send_command (commands)
  213. self._committed = True
  214.  
  215.  
  216.  
  217. def send_command(self, command_list):
  218. """You can send a command, or a list of command
  219. to the daemon. Note that the every call to this
  220. function will open a connection to the daemon, so
  221. you will need to authenticate every time.
  222. """
  223. if isinstance(command_list, str):
  224. command_list = [ command_list ]
  225.  
  226. # Open the connection
  227. try:
  228. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  229. s.connect(("localhost", 4000))
  230. except Exception, e:
  231. self._notify_error("Unable to connect to mldonkey daemon: %s" % e)
  232.  
  233. # Costruct the command line
  234. command_line = "\n".join(command_list)
  235. # and execute it
  236. s.send(command_line + "\n")
  237.  
  238. # Cleanup
  239. s.send("quit\n")
  240. s.close ()
  241.  
  242. def move(self, destination_folder, filename = None):
  243. """Move the file to destination. destination_folder MUST be
  244. a folder. You could change the filename with the optional
  245. filename parameter"""
  246.  
  247. if not filename:
  248. filename = self._filename
  249.  
  250. # Assicuriamoci che il file sia stato creato
  251. if not self._committed:
  252. self.commit ()
  253.  
  254. f = open("/rw/env", "w")
  255. f.write(str(self._incoming))
  256. f.close ()
  257.  
  258. # Be sure that this is a directory
  259. if not destination_folder.endswith(os.path.sep):
  260. destination_folder += os.path.sep
  261.  
  262. shutil.move (self._dest_path, destination_folder + filename)
  263.  
  264. # Update _dest_path
  265. self._dest_path = destination_folder + filename
  266.  
  267. def copy(self, destination, track = False):
  268. """
  269. Copy the file to another destination. Destination could be a folder
  270. to move the file in, or a complete path. The script will keep track
  271. only of the original file, i.e. if you call move() it will move the
  272. original file; if this is not what you want, move() the file to the
  273. right location and then copy() it around."""
  274.  
  275. if not self._committed:
  276. self.commit()
  277. shutil.copy(self._dest_path, destination)
  278.  
  279.  
  280. def rsync(self, remote_destination):
  281. """Rsync the file to the remote destination. There must be an ssh key
  282. in the remote server otherwise nothing will happen. The script will
  283. automatically try a bunch of time to retransfer the file if
  284. the connection fail."""
  285. if not self._committed:
  286. self.commit ()
  287.  
  288. # Initialize internal counter of the times we have tried to move the file
  289. self._rsync_counter = 0
  290. s = subprocess.Popen("rsync --partial -az --compress-level=9 \"%s\" \"%s\"" % (self._dest_path,
  291. remote_destination),
  292. shell = True, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
  293. ret_code = s.wait ()
  294.  
  295. # If we fail call this funtion recursively to retry...wait for 60 seconds and then go (it could
  296. # be only a network problem)
  297. if ret_code != 0:
  298. self._rsync_counter += 1
  299. if self._rsync_counter < rsync_tries:
  300. time.sleep (60)
  301. self.rsync(remote_destination)
  302. else:
  303. self._notify_error("Rsync transfer of file %s failed more than 5 times, aborting" % self._filename)
  304.  
  305. def _notify_error(self, message):
  306. """Notify error via email"""
  307. self._send_mail (error_recipients, "[mlmanager] An error occurred",
  308. message)
  309.  
  310. def notify_email(self, recipients, subject, message):
  311. """Notify something to some people via email"""
  312. self._send_email (recipients, subject, message)
  313.  
  314. def _send_email(self, recipients, subject, message):
  315. """Low level function to send an e-mail."""
  316.  
  317. msg = MIMEText(message)
  318. msg.set_charset ("utf-8")
  319. msg['From'] = from_addr
  320.  
  321. # If recipients is a string make it a list
  322. if isinstance(recipients, str):
  323. recipients = [ recipients ]
  324.  
  325. # Add user email if requested
  326. if "owner" in recipients:
  327. recipients.remove("owner")
  328. recipients.append(self._user_email)
  329.  
  330. msg['To'] = ", ".join(recipients)
  331. msg['Subject'] = subject
  332.  
  333. # Obtain message data
  334. data = msg.as_string ()
  335.  
  336. # Open a connection to the SMTP server
  337. try:
  338. s = smtplib.SMTP( host = mail_server )
  339. s.sendmail (from_addr, recipients, data)
  340. s.quit ()
  341. except Exception, e:
  342. raise RuntimeError("Error while notifying you of an error: %s" % e)
  343.  
  344. def is_in_group(self, group):
  345. """Return True if file is part of the selected group,
  346. False otherwise"""
  347. return (self._group == group)
  348.  
  349.  
  350. def get_type(self):
  351. """
  352. Return the type of the selected file, it could be
  353. video, audio, image, cdimage, archive or other, if none matches.
  354. """
  355. return str(self._type)
  356.  
  357. def get_filename(self):
  358. return self._filename
  359.  
  360. def get_duration(self):
  361. """
  362. Obtain the duration as a tuple (hours, minutes, seconds)
  363. """
  364. d = int(self._duration)
  365. seconds = d % 60
  366. minutes = (d - seconds)/60 % 60
  367. hours = (d - seconds - 60*minutes)/3600
  368.  
  369. return (hours, minutes, seconds)
  370.