Best Python code snippet using pyatom_python
showparticle.py
Source:showparticle.py
1#2# 3# 4# 5# 6# 7import requests8import json9# 10# 11# 12def rcp(particle, pid, jsonrpcid):13 url = "http://localhost:4000/jsonrpc"14 headers = {'content-type': 'application/json'}15 payload = {16 "method": "addParticle",17 "params": ['{"event":"debugger", "command":"get ' + particle + ' ' + pid + '"}'],18 "jsonrpc": "2.0",19 "id": jsonrpcid, }20 jsonrpcid = jsonrpcid + 121 #22 result = requests.post(url, data=json.dumps(payload),headers=headers).json()23 return json.loads(result['result'])24# 25def showPartcile(showlist): 26 #27 jsonrpcid = 128 #29 if (len(showlist) != 3): 30 print('\nError:> The number of arguments to the st command is incorrect.')31 print(' For example: sh syslog 5364716253\n')32 return True33 #34 if (showlist[1] == 'prediction'):35 #36 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']37 if (xjson == 'NULL'):38 print('\n---- PREDICTION/Partcile Type := [STIX] ----------------------------------------')39 print('ERROR: No PREDICTION Identifier found in Database or Cache.')40 print('----------------------------------------------------------------------------------')41 return True42 # 43 for i in xjson:44 print('---- Event Type := [PREDICTION] -------------------------------------------------------')45 print(' ID Chain := [PREDICTION:',xjson[i]['identifier'],']')46 print('PREDICTION Type :=', xjson[i]['type'])47 print('PREDICTION Identifier :=', xjson[i]['identifier'])48 print('PREDICTION Date & Time :=', xjson[i]['datetime'])49 print('PREDICTION References :=', xjson[i]['references'])50 print('--------------------------------------------------------------------------------')51 if (showlist[1] == 'stix'):52 #53 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']54 if (xjson == 'NULL'):55 print('\n---- STIX/Partcile Type := [STIX] --------------------------------------------')56 print('ERROR: No STIX Identifier found in Database or Cache.')57 print('----------------------------------------------------------------------------------')58 return True59 # 60 for i in xjson:61 print('\n---- Event Type := [STIX] -------------------------------------------------------')62 print(' ID Chain := [STIX:',xjson[i]['identifier'],']')63 print('STIX Type :=', xjson[i]['type'])64 print('STIX Name :=', xjson[i]['name'])65 print('STIX Identifier :=', xjson[i]['identifier'])66 print('STIX Description :=', xjson[i]['description'])67 print('STIX Creation Time :=', xjson[i]['cdatetime'])68 print('STIX Modification Time :=', xjson[i]['mdatetime'])69 print('STIX Description :=', xjson[i]['description'])70 print('STIX Pattern :=', xjson[i]['pattern'])71 print('STIX Kill Chain Phase :=', xjson[i]['killchainphase'])72 print('STIX Labels :=', xjson[i]['lables'])73 print('STIX External Refs :=', xjson[i]['externalrefs'])74 print('STIX Relationship Type :=', xjson[i]['relationship_type'])75 print('STIX Source Reference :=', xjson[i]['source_ref'])76 print('STIX Target Reference :=', xjson[i]['target_ref']) 77 print('--------------------------------------------------------------------------------') 78 elif (showlist[1] == 'event'):79 #80 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']81 if (xjson == 'NULL'):82 print('\n---- Event/Partcile Type := [EVENT] --------------------------------------------')83 print('ERROR: No Event Identifier found in Database or Cache.')84 print('----------------------------------------------------------------------------------')85 return True86 #87 for i in xjson:88 print('\n---- Event/Partcile Type := [EVENT] --------------------------------------------')89 print('ID Chain := [EVENT:',xjson[i]['identifier'],']')90 print('Event Identifier :=', xjson[i]['identifier'])91 print('Event Date and Time :=', xjson[i]['datetime'])92 print('Event Sub Type :=', xjson[i]['subtype'])93 print('Event Sub Type Ident :=', xjson[i]['sub_id'], '\n')94 print('----------------------------------------------------------------------------------')95 #96 elif (showlist[1] == 'syslog'):97 #98 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']99 if (xjson == 'NULL'):100 print('\n---- Event/Partcile Type := [SYSLOG] -------------------------------------------')101 print('ERROR: No Syslog Identifier found in Database or Cache.')102 print('----------------------------------------------------------------------------------')103 return True104 #105 for i in xjson:106 print('\n---- Event/Partcile Type := [EVENT]->[SYSLOG] ----------------------------------')107 print(' ID Chain := [EVENT:',xjson[i]['suptype_id'],']->[SYSLOG:',xjson[i]['identifier'],']')108 print(' Identifier :=', xjson[i]['identifier'])109 print(' Date and Time :=', xjson[i]['datetime'])110 print(' Super Type[Identifier] :=', xjson[i]['suptype'], '[', xjson[i]['suptype_id'], ']')111 print(' Sub Type[Identifier] :=', xjson[i]['subtype'], '[', xjson[i]['subtype_id'], ']')112 print(' System :=', xjson[i]['system'])113 print(' Process[Identifier] :=', xjson[i]['process_name'],'[', xjson[i]['process_id'], ']')114 print(' Message :=', xjson[i]['data'], '\n')115 print('----------------------------------------------------------------------------------')116 #117 elif (showlist[1] == 'snort'):118 #119 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']120 if (xjson == 'NULL'):121 print('\n---- Event/Partcile Type := [SNORT] --------------------------------------------')122 print('ERROR: No Snort Identifier found in Database or Cache.')123 print('----------------------------------------------------------------------------------')124 return True125 #126 for i in xjson: 127 print('\n---- Event/Partcile Type := [EVENT]->[SYSLOG]->[SNORT] --------------------------')128 print(' ID Chain := [SYSLOG:',xjson[i]['suptype_id'],']->[SNORT:',xjson[i]['identifier'],']')129 print(' Identifier :=', xjson[i]['identifier'])130 print(' Date and Time :=', xjson[i]['datetime'])131 print(' System :=', xjson[i]['system'])132 print(' Version :=', xjson[i]['version'])133 print(' Classification :=', xjson[i]['classification'])134 print(' Priority :=', xjson[i]['priority'])135 print(' |----> Protocol :=', xjson[i]['protocol'])136 print(' |----> Snort Alert Message :=', xjson[i]['message'])137 print(' |----> SRC IP Address :=', xjson[i]['src'])138 print(' |----> SRC Port Address :=', xjson[i]['srcport'])139 print(' |----> DST IP Address :=', xjson[i]['dst'])140 print(' |----> DST Port Address :=', xjson[i]['dstport'])141 #142 elif (showlist[1] == 'sshd'):143 #144 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']145 if (xjson == 'NULL'):146 print('\n---- Event/Partcile Type := [SSHD] ---------------------------------------------')147 print('ERROR: No SSHD Identifier found in Database or Cache.')148 print('----------------------------------------------------------------------------------')149 return True150 #151 for i in xjson: 152 print('\n---- Event/Partcile Type := [EVENT]->[SYSLOG]->[SSHD] --------------------------')153 print(' ID Chain := [SYSLOG:',xjson[i]['suptype_id'],']->[SSHD:',xjson[i]['identifier'],']')154 print(' Identifier :=', xjson[i]['identifier'])155 print(' Date and Time :=', xjson[i]['datetime'])156 print(' System :=', xjson[i]['system'])157 print(' Process :=', xjson[i]['process'])158 print(' Source IP Address :=', xjson[i]['sourceaddr'])159 print(' Source Port :=', xjson[i]['sourceport'])160 print(' Username :=', xjson[i]['username'])161 print(' Raw Data :=', xjson[i]['data'])162 #163 print('--------------------------------------------------------------------------------')164 #165 elif (showlist[1] == 'vsftpd'):166 #167 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']168 if (xjson == 'NULL'):169 print('\n---- Event/Partcile Type := [VSFTPD] -------------------------------------------')170 print('ERROR: No VSFTPD Identifier found in Database or Cache.')171 print('----------------------------------------------------------------------------------')172 return True173 #174 for i in xjson: 175 print('\n---- Event/Partcile Type := [EVENT]->[SYSLOG]->[VSFTPD] --------------------------')176 print(' ID Chain := [SYSLOG:',xjson[i]['suptype_id'],']->[VSFTPD:',xjson[i]['identifier'],']')177 print(' Identifier :=', xjson[i]['identifier'])178 print(' Date and Time :=', xjson[i]['datetime'])179 print(' Username :=', xjson[i]['username'])180 print(' Command Type :=', xjson[i]['commandtype'])181 print(' Source Address :=', xjson[i]['sourceaddr'])182 print(' Raw Data :=', xjson[i]['data'])183 #184 print('--------------------------------------------------------------------------------')185 #186 elif (showlist[1] == 'tcpd'):187 #188 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']189 if (xjson == 'NULL'):190 print('\n---- Event/Partcile Type := [TCPD] ---------------------------------------------')191 print('ERROR: No TCPD Identifier found in Database or Cache.')192 print('----------------------------------------------------------------------------------')193 return True194 #195 for i in xjson:196 print('\n---- Event/Partcile Type := [EVENT]->[SYSLOG]->[TCPD] --------------------------')197 print(' ID Chain := [SYSLOG:',xjson[i]['suptype_id'],']->[TCPD:',xjson[i]['identifier'],']')198 print(' Identifier :=', xjson[i]['identifier'])199 print(' Date and Time :=', xjson[i]['datetime'])200 print(' System :=', xjson[i]['system'])201 print(' Process :=', xjson[i]['process'])202 print(' Connection :=', xjson[i]['connection'])203 #204 print('--------------------------------------------------------------------------------')205 #206 elif (showlist[1] == 'cef'):207 #208 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']209 if (xjson == 'NULL'):210 print('\n---- Event/Partcile Type := [CEF] ----------------------------------------------')211 print('ERROR: No CEF Identifier found in Database or Cache.')212 print('----------------------------------------------------------------------------------')213 return True214 #215 for i in xjson:216 print('\n---- Event/Partcile Type := [EVENT]->[SYSLOG]->[CEF] --------------------------')217 print(' ID Chain := [SYSLOG:',xjson[i]['suptype_id'],']->[CEF:',xjson[i]['identifier'],']')218 print(' Identifier :=', xjson[i]['identifier'])219 print(' Date and Time :=', xjson[i]['datetime'])220 print(' Version :=', xjson[i]['version'])221 print(' Device Info :=', xjson[i]['deviceinfo'])222 print(' Source IP Address :=', xjson[i]['sourceip'])223 print(' CEF Signature :=', xjson[i]['signature'])224 print(' Severity :=', xjson[i]['severity'])225 print(' CEF Exenstions :=', xjson[i]['exenstions'])226 #227 print('--------------------------------------------------------------------------------')228 #229 elif (showlist[1] == 'nsca'):230 #231 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']232 if (xjson == 'NULL'):233 print('\n---- Event/Partcile Type := [NSCA] ---------------------------------------------')234 print('ERROR: No NCSA Identifier found in Database or Cache.')235 print('----------------------------------------------------------------------------------')236 return True237 #238 for i in xjson:239 print('\n---- Event/Partcile Type := [EVENT]->[NSCA] ------------------------------------')240 print(' ID Chain := [EVENT:',xjson[i]['suptype_id'],']->[NSCA:',xjson[i]['identifier'],']')241 print(' Identifier :=', xjson[i]['identifier'])242 print(' Date and Time :=', xjson[i]['datetime'])243 print(' Client :=', xjson[i]['client'])244 print(' User ID :=', xjson[i]['userid'])245 print(' User :=', xjson[i]['user'])246 print(' NSCA Request :=', xjson[i]['request'])247 print(' Status Code :=', xjson[i]['statuscode'])248 print(' The Size :=', xjson[i]['size'])249 #250 print('--------------------------------------------------------------------------------')251 elif (showlist[1] == 'dns'):252 #253 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']254 if (xjson == 'NULL'):255 print('\n---- Event/Partcile Type := [DNS] ----------------------------------------------')256 print('ERROR: No DNS Identifier found in Database or Cache.')257 print('----------------------------------------------------------------------------------')258 return True259 #260 for i in xjson:261 print('\n---- Event/Partcile Type := [EVENT]->[DNS] -----------------------------------')262 print(' ID Chain := [EVENT:',xjson[i]['suptype_id'],']->[DNS:',xjson[i]['identifier'],']')263 print(' Identifier :=', xjson[i]['identifier'])264 print(' Date and Time :=', xjson[i]['datetime'])265 print(' Requester :=', xjson[i]['requester'])266 print(' DNS Request :=', xjson[i]['request'])267 print(' DNS Request Type :=', xjson[i]['requesttype'])268 #269 print('--------------------------------------------------------------------------------')270 elif (showlist[1] == 'netflow'):271 #272 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']273 if (xjson == 'NULL'):274 print('\n---- Event/Partcile Type := [NETFLOW] ------------------------------------------')275 print('ERROR: No NetFlow Identifier found in Database or Cache.')276 print('----------------------------------------------------------------------------------')277 return True278 #279 for i in xjson:280 print('\n---- Event/Partcile Type := [EVENT]->[NETFLOW] ----------------------------------')281 print(' ID Chain := [EVENT:',xjson[i]['suptype_id'],']->[NETFLOW:',xjson[i]['identifier'],']')282 print(' Identifier :=', xjson[i]['identifier'])283 print(' Date and Time :=', xjson[i]['datetime'])284 print(' Duration of Flow :=', xjson[i]['duration'])285 print(' Protocol :=', xjson[i]['protocol'])286 print(' Source IP Addrress :=', xjson[i]['sourceip'])287 print(' Source Port :=', xjson[i]['sourceport'])288 print(' Dest IP Address :=', xjson[i]['destinationip'])289 print(' Destination Port :=', xjson[i]['destport'])290 print(' No of Packets :=', xjson[i]['packets'])291 print(' No of Bytes in Flow :=', xjson[i]['pbytes'])292 #293 print('--------------------------------------------------------------------------------')294 elif (showlist[1] == 'ftpd'):295 #296 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']297 if (xjson == 'NULL'):298 print('\n---- Event/Partcile Type := [FTPD] ---------------------------------------------')299 print('ERROR: No FTPD Identifier found in Database or Cache.')300 print('----------------------------------------------------------------------------------')301 return True302 #303 for i in xjson:304 print('\n---- Event/Partcile Type := [EVENT]->[FTPDDDDD] ----------------------------------')305 print(' ID Chain := [EVENT:',xjson[i]['suptype_id'],']->[FTPD:',xjson[i]['identifier'],']')306 print(' Identifier :=', xjson[i]['identifier'])307 print(' Date and Time :=', xjson[i]['datetime'])308 print(' Transfer Time :=', xjson[i]['transfertime'])309 print(' Remote Host :=', xjson[i]['remotehost'])310 print(' Filesize :=', xjson[i]['filesize'])311 print(' FTP Filename :=', xjson[i]['filename'])312 print(' Transfer Type :=', xjson[i]['transfertype'])313 print(' Action Flag :=', xjson[i]['actionflag'])314 print(' FTP Direction :=', xjson[i]['direction'])315 print(' Access Mode :=', xjson[i]['accessmode'])316 print(' Username :=', xjson[i]['username'])317 print(' Service Name :=', xjson[i]['servicename'])318 print(' Auth Method :=', xjson[i]['authmethod'])319 print(' Authuser ID :=', xjson[i]['authuserid'])320 print(' FTP Status Code :=', xjson[i]['status'])321 #322 print('--------------------------------------------------------------------------------')323 elif (showlist[1] == 'evt'):324 #325 xjson = rcp(showlist[1], showlist[2], jsonrpcid)['data']326 if (xjson == 'NULL'):327 print('\n---- Event/Partcile Type := [EVT] ----------------------------------------------')328 print('ERROR: No Micorosft Windows Event(EVT) Identifier found in Database or Cache.')329 print('----------------------------------------------------------------------------------')330 return True331 #332 for i in xjson:333 print('\n---- Event/Partcile Type := [EVENT]->[EVT] ----------------------------------')334 print(' ID Chain := [EVENT:',xjson[i]['suptype_id'],']->[EVT:',xjson[i]['identifier'],']')335 print(' Identifier :=', xjson[i]['identifier'])336 print(' Date and Time :=', xjson[i]['datetime'])337 print(' Event ID :=', xjson[i]['eventid'])338 print(' EVT Date & Time :=', xjson[i]['evtdatetime'])339 print(' User :=', xjson[i]['user'])340 print(' Computer :=', xjson[i]['computer'])341 print(' Process ID :=', xjson[i]['processid'])342 print(' Thread ID :=', xjson[i]['threadid'])343 print(' EVT Keywords :=', xjson[i]['keywords'])344 #345 print('--------------------------------------------------------------------------------')346 elif (showlist[1] == 'ip'):347 #348 _ = rcp(showlist[1], showlist[2], jsonrpcid)349 #350 elif (showlist[1] == 'tcp'):351 #352 _ = rcp(showlist[1], showlist[2], jsonrpcid)353 #354 elif (showlist[1] == 'udp'):355 #356 _ = rcp(showlist[1], showlist[2], jsonrpcid)357 #358 elif (showlist[1] == 'icmp'):359 #360 _ = rcp(showlist[1], showlist[2], jsonrpcid)361 #362 elif (showlist[1] == 'tcphttp'):363 #364 _ = rcp(showlist[1], showlist[2], jsonrpcid)365 #366 return True367#368#...
sickbeard.py
Source:sickbeard.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3from __future__ import division4import cherrypy5import pytunes6from urllib import quote7from urllib2 import urlopen8from json import loads9import logging10import cgi11class Sickbeard:12 def __init__(self):13 self.logger = logging.getLogger('modules.sickbeard')14 pytunes.MODULES.append({15 'name': 'Sickbeard',16 'id': 'sickbeard',17 'test': '%ssickbeard/ping' % pytunes.WEBDIR,18 'fields': [19 {'type': 'bool', 'label': 'Enable', 'name': 'sickbeard_enable'},20 {'type': 'text', 'label': 'Menu name', 'name': 'sickbeard_name', 'placeholder':''},21 {'type': 'text', 'label': 'IP / Host *', 'name': 'sickbeard_host', 'placeholder':''},22 {'type': 'text', 'label': 'Port *', 'name': 'sickbeard_port', 'placeholder':'', 'desc':'Default is 8081'},23 {'type': 'text', 'label': 'Basepath', 'name': 'sickbeard_basepath'},24 {'type': 'text', 'label': 'API key', 'name': 'sickbeard_apikey'},25 {'type': 'bool', 'label': 'Use SSL', 'name': 'sickbeard_ssl'}26 ]})27 @cherrypy.expose()28 def index(self, query=''):29 return pytunes.LOOKUP.get_template('sickbeard.html').render(scriptname='sickbeard', query=query)30 @cherrypy.expose()31 def view(self, tvdbid):32 if not (tvdbid.isdigit()):33 raise cherrypy.HTTPError("500 Error", "Invalid show ID.")34 self.logger.error("Invalid show ID was supplied: %s" % str(tvdbid))35 return False36 return pytunes.LOOKUP.get_template('sickbeard_view.html').render(scriptname='sickbeard_view', tvdbid=tvdbid)37 @cherrypy.expose()38 @cherrypy.tools.json_out()39 def ping(self, sickbeard_host, sickbeard_port, sickbeard_apikey, sickbeard_basepath, sickbeard_ssl = False, **kwargs):40 ssl = 's' if sickbeard_ssl else ''41 self.logger.debug("Testing connectivity")42 try:43 if not (sickbeard_basepath.endswith('/')):44 sickbeard_basepath += "/"45 url = 'http%s://%s:%s%sapi/%s/?cmd=sb.ping' % (ssl, sickbeard_host, sickbeard_port, sickbeard_basepath, sickbeard_apikey)46 self.logger.debug("Trying to contact sickbeard via %s" % url)47 response = loads(urlopen(url, timeout=10).read())48 if response.get('result') == "success":49 self.logger.debug("Sicbeard connectivity test success")50 return response51 except:52 self.logger.error("Unable to contact sickbeard via %s" % url)53 return54 @cherrypy.expose()55 @cherrypy.tools.json_out()56 def GetShowList(self):57 self.logger.debug("Fetching Shows list")58 sb_table = []59 sb_table_out = []60 list = self.fetch('shows&sort=name')61 sb_row = "<tr><td><a href='/sickbeard/view/%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td title='Downloaded/Snatched/Wanted/Skipped/Ignored/Unaired/Total'>%s</td><td><div class='progress span2'><div class='bar bar-success' style='width: %s%s;' title='%s Downloaded'></div><div class='bar bar-warning' style='width: %s%s;'title='%s Snatched'></div></div></td></tr>"62 #print list63 for show in list['data']:64 showlist = {}65 showlist['show'] = show66 if show[:4] == 'The ':67 showlist['sortshow'] = show[4:]68 else:69 showlist['sortshow'] = show70 #showlist['sortshow'] = shortshow71 #print show['status']72 #print show['network']73 #print show['quality']74 showlist['nextair'] = list['data'][show]['next_ep_airdate']75 showlist['status'] = list['data'][show]['status']76 showlist['network'] = list['data'][show]['network']77 showlist['quality'] = list['data'][show]['quality']78 showlist['tvdbid'] = list['data'][show]['tvdbid']79 sdata = self.fetch('show.stats&tvdbid=%s' % list['data'][show]['tvdbid'])80 #print sdata81 if sdata['message']:82 print sdata['message'], show83 #log it and put error on prog bar84 continue85 showlist['downloaded'] = sdata['data']['downloaded']['total']86 showlist['snatched'] = sdata['data']['snatched']['total']87 showlist['total'] = sdata['data']['total']88 showlist['unaired'] = sdata['data']['unaired']89 showlist['wanted'] = sdata['data']['wanted']90 showlist['ignored'] = sdata['data']['ignored']91 showlist['skipped'] = sdata['data']['skipped']92 showlist['stats'] = '%s/%s/%s/%s/%s/%s/%s' % (showlist['downloaded'], showlist['snatched'], showlist['wanted'], showlist['skipped'], showlist['ignored'], showlist['unaired'], showlist['total'])93 showlist['percent_downloaded'] = 094 showlist['percent_snatched'] = 095 if showlist['total']:96 showlist['percent_downloaded'] = 100*(showlist['downloaded']/showlist['total'])97 showlist['percent_snatched'] = 100*(showlist['snatched']/showlist['total'])98 #print downloaded, snatched99 #print stats100 sb_table.append(showlist)101 for showrow in sorted(sb_table, key=lambda k: k['sortshow']):102 if showrow['status'] == 'Continuing':103 status = "<span class='label label-success'><i class='icon-repeat icon-white' /> %s</span>" % showrow['status']104 else: 105 status = "<span class='label label-important'><i class='icon-remove icon-white' /> %s</span>" % showrow['status']106 if showrow['quality'] in ['HD720p', 'HD TV', 'HD 1080p', 'HD']:107 quality = "<span class='label label-info'>%s</span>" % showrow['quality']108 else:109 quality = "<span class='label label-warning'>%s</span>" % showrow['quality']110 sb_table_out.append(sb_row % (showrow['tvdbid'], showrow['show'], status, showrow['nextair'], showrow['network'], quality, showrow['stats'], showrow['percent_downloaded'], '%', showrow['downloaded'], showrow['percent_snatched'], '%', showrow['snatched']))111 #print ''.join(sb_table_out)112 return ''.join(sb_table_out)113 114 #return self.fetch('shows&sort=name')115 @cherrypy.expose()116 @cherrypy.tools.json_out()117 def GetNextAired(self):118 self.logger.debug("Fetching Next Aired Episodes")119 return self.fetch('future')120 @cherrypy.expose()121 def GetBanner(self, tvdbid):122 self.logger.debug("Fetching Banner")123 cherrypy.response.headers['Content-Type'] = 'image/jpeg'124 return self.fetch('show.getbanner&tvdbid=%s' % tvdbid, True)125 @cherrypy.expose()126 def GetPoster(self, tvdbid):127 self.logger.debug("Fetching Poster")128 cherrypy.response.headers['Content-Type'] = 'image/jpeg'129 return self.fetch('show.getposter&tvdbid=%s' % tvdbid, True)130 @cherrypy.expose()131 @cherrypy.tools.json_out()132 def GetHistory(self, limit=''):133 self.logger.debug("Fetching History")134 return self.fetch('history&limit=%s' % limit)135 @cherrypy.expose()136 @cherrypy.tools.json_out()137 def GetLogs(self):138 self.logger.debug("Fetching Logs")139 return self.fetch('logs&min_level=info')140 @cherrypy.expose()141 @cherrypy.tools.json_out()142 def AddShow(self, tvdbid):143 self.logger.debug("Adding a Show")144 return self.fetch('show.addnew&tvdbid=%s' % tvdbid)145 @cherrypy.expose()146 @cherrypy.tools.json_out()147 def GetShow(self, tvdbid):148 149 self.logger.debug("Fetching Show")150 return self.fetch('show&tvdbid=%s' % tvdbid)151 @cherrypy.expose()152 @cherrypy.tools.json_out()153 def GetSeason(self, tvdbid, season):154 self.logger.debug("Fetching Season")155 return self.fetch('show.seasons&tvdbid=%s&season=%s' % (tvdbid, season))156 @cherrypy.expose()157 @cherrypy.tools.json_out()158 def SearchEpisodeDownload(self, tvdbid, season, episode):159 self.logger.debug("Fetching Episode Downloads")160 return self.fetch('episode.search&tvdbid=%s&season=%s&episode=%s' % (tvdbid, season, episode), False, 45)161 @cherrypy.expose()162 @cherrypy.tools.json_out()163 def RemoveShow(self, tvdbid):164 self.logger.debug("Force full update for tvdbid %s" % tvdbid)165 return self.fetch("show.delete&tvdbid=%s" % tvdbid)166 @cherrypy.expose()167 @cherrypy.tools.json_out()168 def ChangeStatus(self):169 self.logger.debug("Changing Show Status")170 form = cgi.FieldStorage()171 name = form.getfirst('statusSelect', 'empty')172 status = cgi.escape(statusSelect)173 episodes = form.getlist('changestatus')174 for each in episodes:175 tvdbid, season, episode = cgi.escape(each).split('|')176 self.fetch("episode.setstatus&tvdbid=%s&season=%s&episode=%s&status=%s" % (tvdbid, season, episode, status)) 177 return178 @cherrypy.expose()179 @cherrypy.tools.json_out()180 def Restart(self):181 self.logger.debug("Restarting Sickbeard")182 return self.fetch("sb.restart")183 @cherrypy.expose()184 @cherrypy.tools.json_out()185 def Shutdown(self):186 self.logger.debug("Shutting Down Sickbeard")187 return self.fetch("sb.shutdown")188 @cherrypy.expose()189 @cherrypy.tools.json_out()190 def ForceFullUpdate(self, tvdbid):191 self.logger.debug("Force full update for tvdbid %s" % tvdbid)192 return self.fetch("show.update&tvdbid=%s" % tvdbid)193 @cherrypy.expose()194 @cherrypy.tools.json_out()195 def RescanFiles(self, tvdbid):196 self.logger.debug("Rescan all local files for tvdbid %s" % tvdbid)197 return self.fetch("show.refresh&tvdbid=%s" % tvdbid)198 @cherrypy.expose()199 def SearchShow(self, query):200 try:201 url = 'http://www.thetvdb.com/api/GetSeries.php?seriesname=%s' % quote(query)202 return urlopen(url, timeout=10).read()203 except:204 return205 def fetch(self, cmd, img=False, timeout=10):206 try:207 host = pytunes.settings.get('sickbeard_host', '')208 port = str(pytunes.settings.get('sickbeard_port', ''))209 apikey = pytunes.settings.get('sickbeard_apikey', '')210 ssl = 's' if pytunes.settings.get('sickbeard_ssl', 0) else ''211 sickbeard_basepath = pytunes.settings.get('sickbeard_basepath', '/')212 if not (sickbeard_basepath.endswith('/')):213 sickbeard_basepath += "/"214 url = 'http%s://%s:%s%sapi/%s/?cmd=%s' % (ssl, host, str(port), sickbeard_basepath, apikey, cmd)215 self.logger.debug("Fetching information from: %s" % url)216 if (img == True):217 return urlopen(url, timeout=timeout).read()218 return loads(urlopen(url, timeout=timeout).read())219 except:220 self.logger.error("Unable to fetch information")...
apicache.py
Source:apicache.py
1#2# Network Ten CatchUp TV Video Addon3#4# Copyright (c) 2013 Adam Malcontenti-Wilson5# 6# Permission is hereby granted, free of charge, to any person obtaining a copy7# of this software and associated documentation files (the "Software"), to deal8# in the Software without restriction, including without limitation the rights9# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10# copies of the Software, and to permit persons to whom the Software is11# furnished to do so, subject to the following conditions:12# 13# The above copyright notice and this permission notice shall be included in14# all copies or substantial portions of the Software.15# 16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22# THE SOFTWARE.23#24import config25from networktenvideo.api import NetworkTenVideo26try:27 import simplejson as json28except ImportError:29 try:30 import deps.simplejson as json31 except ImportError:32 import json33class APICache:34 def __init__(self, plugin=None):35 self.api = NetworkTenVideo()36 self.log = plugin.log37 self.log.debug('Cache TTL set to %d minutes', config.CACHE_TTL)38 self.cache = plugin.get_storage('showlist', TTL=config.CACHE_TTL)39 print repr(self.cache)40 def get_show(self, show, bypassCache=False):41 if not bypassCache and 'showlist' in self.cache and show in self.cache['showlist']:42 self.log.debug('Retrieving show data for show "%s" from cache...', show)43 show_data = self.cache['showlist'][show]44 else:45 self.log.debug('Retrieving show data for show "%s" from api ...', show)46 show_data = self.api.get_show(show)47 if not 'showlist' in self.cache:48 self.cache['showlist'] = {}49 self.cache['showlist'][show_data.showName] = show_data50 self.cache.sync()51 self.log.debug('Show data: %s', repr(show_data))52 return show_data53 def get_shows(self, bypassCache=False):54 if not bypassCache and 'showlist' in self.cache:55 self.log.debug('Retrieving show list from cache...')56 shows = self.cache['showlist'].values()57 else:58 self.log.debug('Retrieving show list from api...')59 shows = self.api.get_shows().items60 if not 'showlist' in self.cache:61 self.cache['showlist'] = {}62 for show in shows:63 self.cache['showlist'][show.showName] = show64 self.cache.sync()65 self.log.debug('Shows: %s', repr(shows))66 return shows67 def get_playlists(self, show, bypassCache=False):68 if not bypassCache and 'showlist' in self.cache and show in self.cache['showlist'] and self.cache['showlist'][show].playlists and len(self.cache['showlist'][show].playlists) > 0:69 self.log.debug('Retrieving playlists for show "%s" from cache...', show)70 playlists = self.cache['showlist'][show].playlists71 else:72 self.log.debug('Retrieving playlists for show "%s" from api...', show)73 playlists = self.api.get_playlists_for_show(show).items74 if show in cache['showlist']:75 self.cache['showlist'][show].playlists = playlists76 self.cache.sync()77 self.log.debug('Playlists: %s', repr(playlists.items))78 return playlists79 def search_videos(self, bypassCache=False, **kwargs):80 key = json.dumps(kwargs)81 print repr(key)82 if not bypassCache and 'searches' in self.cache and key in self.cache['searches']:83 self.log.debug('Using search results from cache...')84 result = self.cache['searches'][key]85 else:86 self.log.debug('Using search results from api...')87 result = self.api.search_videos(**kwargs)88 if not 'searches' in self.cache:89 self.cache['searches'] = {}90 self.cache['searches'][key] = result91 self.cache.sync()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!