Advertisement
HiImTye

Launchers/.tconk-scripts-conkyDeluge.py

Apr 8th, 2014
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 29.67 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. ###############################################################################
  4. # conkyDeluge.py is a simple python script to gather
  5. # details of Deluge torrents for use in conky.
  6. #
  7. # Author: Kaivalagi
  8. # Created: 13/10/2008
  9. #
  10. #Modified:
  11. #    13/10/2008    Fixed progress % issue with multi-file torrents
  12. #    14/10/2008    Added expected time of arrival (eta) as an output, can be used in the template with <eta>
  13. #    17/10/2008    Updated to import and use deluge sclient and common formatting functions, disabled deluge logging functions too
  14. #    17/10/2008    Updated to use "progress", "eta", "download_payload_rate", "upload_payload_rate" dictionary data to avoid invalid calculations
  15. #    17/10/2008    --version now only returns version and doesn't try to display normal output too
  16. #    30/10/2008    Updated error handling for when no torrent status data available, issues usually happen when half way through torrents output and a torrent is no longer there
  17. #    30/10/2008    Added --errorlogfile and infologfile options, when set with a filepath, errors and info are appended to the filepath given
  18. #    02/11/2008    Added --downloadsonly option to limit output to only currently active torrents in a downloading state
  19. #    03/11/2008    Added currentpeers, currentseeds, totalpeers, totalseeds and ratio to the data available
  20. #    03/11/2008    Updated to output text in utf-8 format, in case of strange characters used in torrent names etc
  21. #    06/11/2008    Replaced the --downloadonly option with --activeonly, when used torrent output is only printed if there are active peers or seeds
  22. #    06/11/2008    Renamed --template option to be called --torrenttemplate as it relates to individual torrent information
  23. #    06/11/2008    Added --showsummary and --summarytemplate options to facilitate the displaying of summary information for all torrents. If --showsummary is used no torrent details are output. This is affected by the --activeonly option.
  24. #    09/11/2008    Updated to collect torrent data into a class list to allow sorting (highest to lowest progress)
  25. #    09/11/2008    Added --limit option to restrict the number of torrents displayed
  26. #    12/11/2008    Now handles when Deluge is not running, and skips doing template prep that isn't required
  27.  
  28. #    15/11/2008    Now loading the template file in unicode mode to allow for the extended character set
  29. #    18/11/2008    Added --hidetorrentdetail option, so both all combinations of output can be output in one exec call
  30. #    18/11/2008    Added <totaleta> to the summary, basically displaying the highest eta for all torrents
  31. #    18/11/2008    Changed option tags from <...> to [...], so <eta> now needs to be [eta] in the template to work
  32. #    08/02/2009    Changed to use total_wanted stats (only selected parts of torrent) instead of total_size, fixes summary progress where partial downloads of torrents are in place
  33.  
  34. #    21/02/2009    Altered the ordering of the output to include state as well as progress, states are listed in the order downloading, seeding, paused, unknown
  35. #    18/04/2009    Updated to retrieve data items for each torrent based on a finite list rather than all of them, this stops an error occuring with python 2.6 and xmlrpc
  36. #    18/05/2009    Updated to expand ~ based template paths
  37. #    26/06/2009    Added --sortby option, takes either "progress", "queue", "eta", "download", "upload" and "ratio" for sorting method.
  38. #                  Also note that a torrent's state supersedes anything else for sorting,
  39. #                  in the order, from top to bottom: downloading, seeding, queued, paused, unknown
  40. #    18/10/2009    Updated to handle new DelugeRPC async methods used in 1.2.0 onwards (will mean this script breaks for previous deluge version users)
  41.  
  42. from datetime import datetime
  43. from deluge.common import ftime, fsize, fspeed
  44. from deluge.ui.client import client
  45. from twisted.internet import reactor
  46. from optparse import OptionParser
  47. import codecs
  48. import logging
  49. import os
  50. import sys
  51. logging.disable(logging.FATAL) #disable logging within Deluge functions, only output info from this script
  52.  
  53. class CommandLineParser:
  54.  
  55.     parser = None
  56.  
  57.     def __init__(self):
  58.  
  59.         self.parser = OptionParser()
  60.         self.parser.add_option("-s","--server", dest="server", type="string", default="127.0.0.1", metavar="SERVER", help=u"[default: %default] The server to connect to where the deluge core is running")
  61.         self.parser.add_option("-p","--port", dest="port", type="int", default=58846, metavar="PORT", help=u"[default: %default] The port to connect to where the deluge core is running")
  62.         self.parser.add_option("-U","--username", dest="username", type="string", metavar="USERNAME", help=u"The username to use when connecting, can be left unset if none is required")
  63.         self.parser.add_option("-P","--password", dest="password", type="string", metavar="PASSWORD", help=u"The password to use when connecting, can be left unset if none is required")
  64.         self.parser.add_option("-S","--showsummary",dest="showsummary", default=False, action="store_true", help=u"Display summary output. This is affected by the --activeonly option.")
  65.         self.parser.add_option("-H","--hidetorrentdetail",dest="hidetorrentdetail", default=False, action="store_true", help=u"Hide torrent detail output, if used no torrent details are output.")
  66.         self.parser.add_option("-t","--torrenttemplate",dest="torrenttemplate", type="string", metavar="FILE", help=u"Template file determining the format for each torrent. Use the following placeholders: [name], [state], [totaldone], [totalsize], [progress], [nofiles], [downloadrate], [uploadrate], [eta], [currentpeers], [currentseeds], [totalpeers], [totalseeds], [ratio].")
  67.         self.parser.add_option("-T","--summarytemplate",dest="summarytemplate", type="string", metavar="FILE", help=u"Template file determining the format for summary output. Use the following placeholders: [notorrents], [totalprogress], [totaldone], [totalsize], [totaldownloadrate], [totaluploadrate], [totaleta], [currentpeers], [currentseeds], [totalpeers], [totalseeds], [totalratio].")
  68.         self.parser.add_option("-a", "--activeonly", dest="activeonly", default=False, action="store_true", help=u"If set only info for torrents in an active state will be displayed.")
  69.         self.parser.add_option("-l","--limit",dest="limit", default=0, type="int", metavar="NUMBER", help=u"[default: %default] Define the maximum number of torrents to display, zero means no limit.")
  70.         self.parser.add_option("-b","--sortby",dest="sortby", default="eta", type="string", metavar="SORTTYPE", help=u"Define the sort method for output, can be \"progress\", \"queue\", \"eta\", \"download\", \"upload\" and \"ratio\". Also note that a torrent's state supersedes anything else for sorting, in the order, from top to bottom: downloading, seeding, queued, paused, unknown)")
  71.         self.parser.add_option("-v","--verbose",dest="verbose", default=False, action="store_true", help=u"Request verbose output, no a good idea when running through conky!")
  72.         self.parser.add_option("-V", "--version", dest="version", default=False, action="store_true", help=u"Displays the version of the script.")
  73.         self.parser.add_option("--errorlogfile", dest="errorlogfile", type="string", metavar="FILE", help=u"If a filepath is set, the script appends errors to the filepath.")
  74.         self.parser.add_option("--infologfile", dest="infologfile", type="string", metavar="FILE", help=u"If a filepath is set, the script appends info to the filepath.")
  75.  
  76.     def parse_args(self):
  77.         (options, args) = self.parser.parse_args()
  78.         return (options, args)
  79.  
  80.     def print_help(self):
  81.         return self.parser.print_help()
  82.  
  83. class TorrentData:
  84.  
  85.     def __init__(self, name, state, statecode, totaldone, totalsize, progress, nofiles, downloadrate, downloadtext, uploadrate, uploadtext, eta, etatext, currentpeers, currentseeds, totalpeers, totalseeds, ratio, queueorder, sortby):
  86.         self.name = name
  87.         self.state = state
  88.         self.statecode = statecode
  89.         self.totaldone = totaldone
  90.         self.totalsize = totalsize
  91.         self.progress = progress
  92.         self.nofiles = nofiles
  93.         self.downloadrate = downloadrate
  94.         self.downloadtext = downloadtext
  95.         self.uploadrate = uploadrate
  96.         self.uploadtext = uploadtext
  97.         self.eta = eta
  98.         self.etatext = etatext
  99.         self.currentpeers = currentpeers
  100.         self.currentseeds = currentseeds
  101.         self.totalpeers = totalpeers
  102.         self.totalseeds = totalseeds
  103.         self.ratio = ratio
  104.         self.queueorder = queueorder
  105.         self.sortby = sortby
  106.  
  107.     def __cmp__(self, other):
  108.         if self.sortby == "progress":
  109.             return cmp(self.getProgressOrder(self.statecode,self.progress) , self.getProgressOrder(other.statecode,other.progress))
  110.         elif self.sortby == "queue":
  111.             return cmp(self.getQueueOrder(self.statecode,self.queueorder) , self.getQueueOrder(other.statecode,other.queueorder))
  112.         elif self.sortby == "eta":
  113.             return cmp(self.getETAOrder(self.statecode,self.eta) , self.getETAOrder(other.statecode,other.eta))
  114.         elif self.sortby == "download":
  115.             return cmp(self.getRateOrder(self.statecode,self.downloadrate) , self.getRateOrder(other.statecode,other.downloadrate))
  116.         elif self.sortby == "upload":
  117.             return cmp(self.getRateOrder(self.statecode,self.uploadrate) , self.getRateOrder(other.statecode,other.uploadrate))
  118.         elif self.sortby == "ratio":
  119.             return cmp(self.getRatioOrder(self.statecode,self.ratio) , self.getRatioOrder(other.statecode,other.ratio))
  120.         else:
  121.             return 0
  122.  
  123.     def __str__(self):
  124.         return str(self.name + " - " + self.eta)
  125.  
  126.     def getProgressOrder(self,statecode,progress):
  127.         return (statecode*10000.0)+float(progress.rstrip("%"))
  128.  
  129.     def getQueueOrder(self,statecode,queueorder):
  130.         if queueorder <> -1:
  131.             queueorder = 1000 - queueorder
  132.         return (statecode*10000.0)+float(queueorder)
  133.  
  134.     def getETAOrder(self,statecode,eta):
  135.         try:
  136.             if eta <> -1:
  137.                 eta = (100000000 - eta)/100
  138.             return (statecode*10000000.0)+float(eta)
  139.         except:
  140.             return 0
  141.  
  142.     def getRateOrder(self,statecode,rate):
  143.         try:
  144.             return (statecode*1000000.0)+float(rate)
  145.         except:
  146.             return 0
  147.  
  148.     def getRatioOrder(self,statecode,ratio):
  149.         try:
  150.             return (statecode*10000.0)+(100.0*float(ratio))
  151.         except:
  152.             return 0
  153.  
  154. class DelugeInfo:
  155.  
  156.     uri = None
  157.     options = None
  158.     sessionstate = None
  159.     sessionstatefound = False
  160.  
  161.     STATE_DOWNLOADING = 4
  162.     STATE_SEEDING = 3
  163.     STATE_QUEUED = 2
  164.     STATE_PAUSED = 1
  165.     STATE_UNKNOWN = 0
  166.  
  167.     def __init__(self, options):
  168.  
  169.         try:
  170.  
  171.             #disable all logging within Deluge functions, only output info from this script
  172.             logging.disable(logging.FATAL)
  173.  
  174.             self.options = options
  175.             self.torrents_status = []
  176.             # sort out the server option
  177.             self.options.server = self.options.server.replace("localhost", "127.0.0.1")
  178.  
  179.             # create the rpc and client objects
  180.             self.d = client.connect(self.options.server, self.options.port, self.options.username, self.options.password)
  181.  
  182.             # We add the callback to the Deferred object we got from connect()
  183.             self.d.addCallback(self.on_connect_success)
  184.  
  185.             # We add the callback (in this case it's an errback, for error)
  186.             self.d.addErrback(self.on_connect_fail)
  187.  
  188.             reactor.run()
  189.  
  190.         except Exception,e:
  191.             self.logError("DelugeInfo Init:Unexpected error:" + e.__str__())
  192.  
  193.     def on_get_torrents_status(self,torrents_status):
  194.  
  195.         self.torrents_status = torrents_status
  196.  
  197.         #for torrentid in torrents_status:
  198.             #print torrentid
  199.             #torrent_status =  torrents_status[torrentid]
  200.  
  201.         # Disconnect from the daemon once we successfully connect
  202.         client.disconnect()
  203.         # Stop the twisted main loop and exit
  204.         reactor.stop()
  205.  
  206.     # We create a callback function to be called upon a successful connection
  207.     def on_connect_success(self,result):
  208.         self.logInfo("Connection successful")
  209.         client.core.get_torrents_status("","").addCallback(self.on_get_torrents_status)
  210.  
  211.     # We create another callback function to be called when an error is encountered
  212.     def on_connect_fail(self,result):
  213.         self.logError("Connection failed! : %s" % result.getErrorMessage())
  214.         reactor.stop()
  215.  
  216.     def getTorrentTemplateOutput(self, template, name, state, totaldone, totalsize, progress, nofiles, downloadrate, uploadrate, eta, currentpeers, currentseeds, totalpeers, totalseeds, ratio):
  217.  
  218.         try:
  219.  
  220.             output = template
  221.  
  222.             output = output.replace("[name]",name)
  223.             output = output.replace("[state]",state)
  224.             output = output.replace("[totaldone]",totaldone)
  225.             output = output.replace("[totalsize]",totalsize)
  226.             output = output.replace("[progress]",progress)
  227.             output = output.replace("[nofiles]",nofiles)
  228.             output = output.replace("[downloadrate]",downloadrate)
  229.             output = output.replace("[uploadrate]",uploadrate)
  230.             output = output.replace("[eta]",eta)
  231.             output = output.replace("[currentpeers]",currentpeers)
  232.             output = output.replace("[currentseeds]",currentseeds)
  233.             output = output.replace("[totalpeers]",totalpeers)
  234.             output = output.replace("[totalseeds]",totalseeds)
  235.             output = output.replace("[ratio]",ratio)
  236.  
  237.             # get rid of any excess crlf's and add just one
  238.             output = output.rstrip(" \n")
  239.             output = output + "\n"
  240.  
  241.             return output
  242.  
  243.         except Exception,e:
  244.             self.logError("getTorrentTemplateOutput:Unexpected error:" + e.__str__())
  245.             return ""
  246.  
  247.     def getSummaryTemplateOutput(self, template, notorrents, totalprogress, totaldone, totalsize, totaldownloadrate, totaluploadrate, totaleta, currentpeers, currentseeds, totalpeers, totalseeds, totalratio):
  248.  
  249.         try:
  250.  
  251.             output = template
  252.  
  253.             output = output.replace("[notorrents]",notorrents)
  254.             output = output.replace("[totalprogress]",totalprogress)
  255.             output = output.replace("[totaldone]",totaldone)
  256.             output = output.replace("[totalsize]",totalsize)
  257.             output = output.replace("[totaldownloadrate]",totaldownloadrate)
  258.             output = output.replace("[totaluploadrate]",totaluploadrate)
  259.             output = output.replace("[totaleta]",totaleta)
  260.             output = output.replace("[currentpeers]",currentpeers)
  261.             output = output.replace("[currentseeds]",currentseeds)
  262.             output = output.replace("[totalpeers]",totalpeers)
  263.             output = output.replace("[totalseeds]",totalseeds)
  264.             output = output.replace("[totalratio]",totalratio)
  265.  
  266.             # get rid of any excess crlf's and add just one
  267.             output = output.rstrip(" \n")
  268.             output = output + "\n"
  269.  
  270.             return output
  271.  
  272.         except Exception,e:
  273.             self.logError("getSummaryTemplateOutput:Unexpected error:" + e.__str__())
  274.             return ""
  275.  
  276.     def writeOutput(self):
  277.  
  278.         try:
  279.  
  280.             self.logInfo("Proceeding with torrent data interpretation...")
  281.  
  282.             torrentDataList = []
  283.             torrentItemList = ["num_peers","num_seeds","name","state","total_done","total_size","total_wanted","progress","files","eta","download_payload_rate","upload_payload_rate","total_peers","total_seeds","ratio","queue"]
  284.             highesteta = 0
  285.  
  286.             # summary variables
  287.             summary_notorrent = 0
  288.             summary_totaldone = 0
  289.             summary_totalsize = 0
  290.             summary_totaldownloadrate = 0.0
  291.             summary_totaluploadrate = 0.0
  292.             summary_totaleta = 0
  293.             summary_currentpeers = 0
  294.             summary_currentseeds = 0
  295.             summary_totalpeers = 0
  296.             summary_totalseeds = 0
  297.             summary_totalratio = 0.0
  298.  
  299.             self.logInfo("Preparing templates...")
  300.  
  301.             if self.options.summarytemplate == None:
  302.                 # create default summary template
  303.                 summarytemplate = "Total Torrents Queued:[notorrents] \n[totaldone]/[totalsize] - [totalprogress]\n" + "DL: [totaldownloadrate] UL: [totaluploadrate]\n"
  304.             else:
  305.                 # load the template file contents
  306.                 try:
  307.                     #fileinput = open(self.options.summarytemplate)
  308.                     fileinput = codecs.open(os.path.expanduser(self.options.summarytemplate), encoding='utf-8')
  309.                     summarytemplate = fileinput.read()
  310.                     fileinput.close()
  311.                 except:
  312.                     self.logError("Summary Template file no found!")
  313.                     sys.exit(2)
  314.  
  315.             if self.options.torrenttemplate == None:
  316.                 # create default template
  317.                 torrenttemplate = "[name]\n[state]\n[totaldone]/[totalsize] - [progress]\n" + "DL: [downloadrate] UL: [uploadrate] ETA:[eta]\n"
  318.             else:
  319.                 # load the template file contents
  320.                 try:
  321.                     #fileinput = open(self.options.torrenttemplate)
  322.                     fileinput = codecs.open(os.path.expanduser(self.options.torrenttemplate), encoding='utf-8')
  323.                     torrenttemplate = fileinput.read()
  324.                     fileinput.close()
  325.                 except:
  326.                     self.logError("Torrent Template file no found!")
  327.                     sys.exit(2)
  328.  
  329.             if len(self.torrents_status) > 0:
  330.  
  331.                 self.logInfo("Processing %s torrent(s)..."%str(len(self.torrents_status)))
  332.  
  333.                 for torrentid in self.torrents_status:
  334.                     torrent_status = self.torrents_status[torrentid]
  335.  
  336.                     if torrent_status != None:
  337.  
  338.                         if self.options.activeonly == True:
  339.  
  340.                             active = False
  341.  
  342.                             # check for activity
  343.                             if "num_peers" in torrent_status:
  344.                                 if torrent_status["num_peers"] > 0:
  345.                                     active = True
  346.  
  347.                             if "num_seeds" in torrent_status:
  348.                                 if torrent_status["num_seeds"] > 0:
  349.                                     active = True
  350.  
  351.                         # output details if all required or if active
  352.                         if self.options.activeonly == False or active == True:
  353.  
  354.                             if "name" in torrent_status:
  355.                                 name = torrent_status["name"]
  356.                             else:
  357.                                 name = "Unknown"
  358.  
  359.                             if "state" in torrent_status:
  360.                                 state = torrent_status["state"]
  361.  
  362.                                 if state == "Downloading":
  363.                                     statecode = self.STATE_DOWNLOADING
  364.                                 elif state == "Seeding":
  365.                                     statecode = self.STATE_SEEDING
  366.                                 elif state == "Queued":
  367.                                     statecode = self.STATE_QUEUED
  368.                                 elif state == "Paused":
  369.                                     statecode = self.STATE_PAUSED
  370.                                 else:
  371.                                     statecode = self.STATE_UNKNOWN
  372.                             else:
  373.                                 state = "Unknown"
  374.                                 statecode = self.STATE_UNKNOWN
  375.  
  376.                             if "total_done" in torrent_status:
  377.                                 totaldone = fsize(torrent_status["total_done"])
  378.                                 summary_totaldone = summary_totaldone + int(torrent_status["total_done"])
  379.                             else:
  380.                                 totaldone = "??.? KiB"
  381.  
  382.                             if "total_size" in torrent_status:
  383.                                 totalsize = fsize(torrent_status["total_wanted"])
  384.                                 summary_totalsize = summary_totalsize + int(torrent_status["total_wanted"])
  385.                             else:
  386.                                 totalsize = "??.? KiB"
  387.  
  388.                             if "progress" in torrent_status:
  389.                                 progress = str(round(torrent_status["progress"],2))+"%"
  390.                             else:
  391.                                 progress = "?.?%"
  392.  
  393.                             if "files" in torrent_status:
  394.                                 nofiles = str(len(torrent_status["files"]))
  395.                             else:
  396.                                 nofiles = "?"
  397.  
  398.                             if "eta" in torrent_status:
  399.                                 eta = torrent_status["eta"]
  400.  
  401.                                 if eta > highesteta:
  402.                                     highesteta = eta
  403.  
  404.                                 etatext = ftime(eta)
  405.                             else:
  406.                                 eta = None
  407.                                 etatext = "Unknown"
  408.  
  409.                             if "download_payload_rate" in torrent_status:
  410.                                 downloadrate = float(torrent_status["download_payload_rate"])
  411.                                 summary_totaldownloadrate = summary_totaldownloadrate + downloadrate
  412.                                 downloadtext = fspeed(downloadrate)
  413.                             else:
  414.                                 downloadrate = 0
  415.                                 downloadtext = "?.? KiB/s"
  416.  
  417.                             if "upload_payload_rate" in torrent_status:
  418.                                 uploadrate = float(torrent_status["upload_payload_rate"])
  419.                                 summary_totaluploadrate = summary_totaluploadrate + uploadrate
  420.                                 uploadtext = fspeed(uploadrate)
  421.                             else:
  422.                                 uploadrate = 0
  423.                                 uploadtext = "?.? KiB/s"
  424.  
  425.                             if "num_peers" in torrent_status:
  426.                                 currentpeers = str(torrent_status["num_peers"])
  427.                                 summary_currentpeers = summary_currentpeers + int(torrent_status["num_peers"])
  428.                             else:
  429.                                 currentpeers = "?"
  430.  
  431.                             if "num_seeds" in torrent_status:
  432.                                 currentseeds = str(torrent_status["num_seeds"])
  433.                                 summary_currentseeds = summary_currentseeds + int(torrent_status["num_seeds"])
  434.                             else:
  435.                                 currentseeds = "?"
  436.  
  437.                             if "total_peers" in torrent_status:
  438.                                 totalpeers = str(torrent_status["total_peers"])
  439.                                 summary_totalpeers = summary_totalpeers + int(torrent_status["total_peers"])
  440.                             else:
  441.                                 totalpeers = "?"
  442.  
  443.                             if "total_seeds" in torrent_status:
  444.                                 totalseeds = str(torrent_status["total_seeds"])
  445.                                 summary_totalseeds = summary_totalseeds + int(torrent_status["total_seeds"])
  446.                             else:
  447.                                 totalseeds = "?"
  448.  
  449.                             if "ratio" in torrent_status:
  450.                                 ratio = str(round(torrent_status["ratio"],3)).ljust(5,"0")
  451.                             else:
  452.                                 ratio = "?.???"
  453.  
  454.                             # for sorting in the same way as progress, we need to order from high to low
  455.                             if "queue" in torrent_status:
  456.                                 queueorder = torrent_status["queue"]
  457.                             else:
  458.                                 queueorder = -1
  459.  
  460.                             sortby = self.options.sortby
  461.  
  462.                             summary_notorrent = summary_notorrent + 1
  463.  
  464.                             # add torrent data to list
  465.                             torrentData = TorrentData(name, state, statecode, totaldone, totalsize, progress, nofiles, downloadrate, downloadtext, uploadrate, uploadtext, eta, etatext, currentpeers, currentseeds, totalpeers, totalseeds, ratio, queueorder, sortby)
  466.                             torrentDataList.append(torrentData)
  467.  
  468.                     else:
  469.                         self.logInfo("No torrent status data available for torrentid: "+torrentid)
  470.  
  471.                 if summary_notorrent > 0:
  472.  
  473.                     output = u""
  474.  
  475.                     if self.options.showsummary == True:
  476.  
  477.                         # sort out summary data for output
  478.                         summary_notorrent = str(summary_notorrent)
  479.                         summary_totalprogress = str(round((float(summary_totaldone) / float(summary_totalsize)) *100,2))+"%"
  480.                         summary_totaldone = fsize(summary_totaldone)
  481.                         summary_totalsize = fsize(summary_totalsize)
  482.                         summary_totaldownloadrate = fspeed(summary_totaldownloadrate)
  483.                         summary_totaluploadrate = fspeed(summary_totaluploadrate)
  484.                         summary_totaleta = ftime(highesteta)
  485.                         summary_currentpeers = str(summary_currentpeers)
  486.                         summary_currentseeds = str(summary_currentseeds)
  487.                         summary_totalpeers = str(summary_totalpeers)
  488.                         summary_totalseeds = str(summary_totalseeds)
  489.                         summary_totalratio = "?.???"
  490.  
  491.                         output = self.getSummaryTemplateOutput(summarytemplate, summary_notorrent, summary_totalprogress, summary_totaldone, summary_totalsize, summary_totaldownloadrate, summary_totaluploadrate, summary_totaleta, summary_currentpeers, summary_currentseeds, summary_totalpeers, summary_totalseeds, summary_totalratio)
  492.  
  493.                     if self.options.hidetorrentdetail == False:
  494.  
  495.                         outputCount = 0
  496.  
  497.                         # sort list, eta based
  498.                         self.logInfo("Sorting torrent list using: %s"%self.options.sortby)
  499.                         torrentDataList.sort(reverse = True)
  500.  
  501.                         # output torrent data using the template
  502.                         for torrentData in torrentDataList:
  503.  
  504.                             # keep a tally of torrent output, if past the limit then exit
  505.                             if self.options.limit <> 0:
  506.                                 outputCount = outputCount + 1
  507.                                 if outputCount > self.options.limit:
  508.                                     break
  509.  
  510.                             output = output + self.getTorrentTemplateOutput(torrenttemplate, torrentData.name, torrentData.state, torrentData.totaldone, torrentData.totalsize, torrentData.progress, torrentData.nofiles, torrentData.downloadtext, torrentData.uploadtext, torrentData.etatext, torrentData.currentpeers, torrentData.currentseeds, torrentData.totalpeers, torrentData.totalseeds, torrentData.ratio)+"\n"
  511.  
  512.                     print output.encode("utf-8")
  513.  
  514.                 else:
  515.                     print u"No torrent info to display"
  516.  
  517.             else:
  518.                 self.logInfo("No torrents found")
  519.  
  520.         except Exception,e:
  521.             self.logError("writeOutput:Unexpected error:" + e.__str__())
  522.  
  523.     def logInfo(self, text):
  524.         if self.options.verbose == True:
  525.             print >> sys.stdout, "INFO: " + text
  526.  
  527.         if self.options.infologfile != None:
  528.             datetimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  529.             fileoutput = open(self.options.infologfile, "ab")
  530.             fileoutput.write(datetimestamp+" INFO: "+text+"\n")
  531.             fileoutput.close()
  532.  
  533.     def logError(self, text):
  534.         print >> sys.stderr, "ERROR: " + text
  535.  
  536.         if self.options.errorlogfile != None:
  537.             datetimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  538.             fileoutput = open(self.options.errorlogfile, "ab")
  539.             fileoutput.write(datetimestamp+" ERROR: "+text+"\n")
  540.             fileoutput.close()
  541.  
  542. def main():
  543.  
  544.     parser = CommandLineParser()
  545.     (options, args) = parser.parse_args()
  546.  
  547.     if options.version == True:
  548.  
  549.         print >> sys.stdout,"conkyDeluge v.2.14.1"
  550.  
  551.     else:
  552.  
  553.         if options.verbose == True:
  554.             print >> sys.stdout, "*** INITIAL OPTIONS:"
  555.             print >> sys.stdout, "    server:",options.server
  556.             print >> sys.stdout, "    port:",options.port
  557.             print >> sys.stdout, "    username:",options.username
  558.             print >> sys.stdout, "    password:",options.password
  559.             print >> sys.stdout, "    showsummary:",options.showsummary
  560.             print >> sys.stdout, "    torrenttemplate:",options.torrenttemplate
  561.             print >> sys.stdout, "    summarytemplate:",options.summarytemplate
  562.             print >> sys.stdout, "    activeonly:",options.activeonly
  563.             print >> sys.stdout, "    limit:",options.limit
  564.             print >> sys.stdout, "    sortby:",options.sortby
  565.             print >> sys.stdout, "    errorlogfile:",options.errorlogfile
  566.             print >> sys.stdout, "    infologfile:",options.infologfile
  567.  
  568.         delugeInfo = DelugeInfo(options)
  569.         if len(delugeInfo.torrents_status) > 0:
  570.             delugeInfo.writeOutput()
  571.  
  572. if __name__ == '__main__':
  573.     main()
  574.     sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement