def menu_account(cookie): ''' Display menu of account list function. :param json cookie: Current session's cookie. ''' lang = language.Language('een_account/operate_account') def printer(string): print(string.replace('\n', '')) while True: [printer(lang.getStrings(x)) for x in range(6)] mode = raw_input('>>> ') if mode == '1': #Display subaccount list. ga.accountlist(cookie) elif mode == '2': #Change account. sa.change_account(cookie) elif mode == '3': #Download and output subaccount list. ga.dl_accountlist(cookie) elif mode == '4': #Return to master account. sa.reset_account(cookie) elif mode == '5': #Display Auth Key. print('auth_key = ' + cookie['auth_key']) elif mode == '0': #Return to menu. print(lang.getStrings(6)) break
def __init__(self): ''' Restore previous cookie and check connection to EEN. :instance_variable json self.cookie: Store the session's cookie. ''' #I don't know why but py2exed program wouldn't make cacert.pem #Comment out below line if use py2exe. #os.environ['REQUESTS_CA_BUNDLE'] = "./certifi/cacert.pem" self.cookie = '' self.lang = language.Language('een_auth/auth') #Try to restore cookie from the cookie file. If it failure then login with user input. try: #Try to restore. with open(Auth.COOKIEFILE, 'r') as f: self.cookie = requests.utils.cookiejar_from_dict(pickle.load(f)) response = requests.get('https://login.eagleeyenetworks.com/g/account/list', cookies=self.cookie) if response.status_code != 200: print(self.lang.getStrings(0).replace('\n','')) #Invalid cookie or the cookie has expired raise IncorrectCookieError except requests.exceptions.ConnectionError: #The internet connection has fault. print(self.lang.getStrings(1).replace('\n','')) #Check internet connection!!! sys.exit() except: #get authentication and authorization. self.__set_cookie()
def apitool_main(): authentica = auth.Auth() #Create a instance of authentication class. cookie = authentica.get_cookie() #Get a cookie. lang = language.Language( 'main') #Create a instance of language localization class. def printer(string): #printer method print(string.replace('\n', '')) while True: [printer(lang.getStrings(x)) for x in range(5)] ''' 1 to device information menu 2 to download videos 3 to change to subaccount 9 to exit with logout 0 to exit without logout ''' mode = raw_input('>>> ') if mode == '1': #Go to devicelist menu. md.menu_bridgeinfo(cookie) elif mode == '2': #Go to download video menu. dv.downloadvideos(cookie) elif mode == '3': #Go to subaccount menu. oa.menu_account(cookie) elif mode == '9': #exit with logout authentica.logout() print(lang.getStrings(5)) #Exiting. break elif mode == '0': #exit without logout print(lang.getStrings(5)) #Exiting. break
def fileout(self, content, gfilename): ''' Make a file from given argument. Accept either JSON or list and write it to a file. This will accept more format if it necessary in future. :param content: This will be content of writen file. it's either JSON or list. :param string filename: the file's name. ''' lang = language.Language('een_filer/export') self.dirname = 'output' self.dirname = od.createdir( self.dirname) #Prepare for failure of making directory self.filename = gfilename try: if type(content) is requests.models.Response: self.__responsewriter(content) elif type(content) is list: self.__listwriter(content) else: raise TypeError print(lang.getStrings(0).replace('\n', '')) #File outputed. except IOError: print(lang.getStrings(1).replace('\n', '')) #File output error!!! except: print(lang.getStrings(2).replace('\n', ''))
def change_account(cookie): ''' Change account method. Ask subaccount's ID and set current master account as a specified subaccount with set_account method. :param strings cookie: Current session's cookie. ''' lang = language.Language('een_account/set_account') print(lang.getStrings(2).replace('\n', '')) #Type sub account ID print(lang.getStrings(3).replace('\n', '')) #Or type "0" to return to menu account = raw_input('>>> ') #Ask subaccount ID if account == 0: #Returning to menu. print(lang.getStrings(4).replace('\n', '')) #Return to menu. else: #Change account. response = set_account(account, cookie) if response.status_code == 200: print(lang.getStrings(5).replace('\n', '')) #Account change success. else: print(lang.getStrings(1).replace('\n', ''))
def inputET(): ''' Accept input of end time of the period. :return string: strings of end of the period for API's URL. ''' lang = language.Language('een_date/set_date') return (eTd2ETs(datecheck(raw_input(lang.getStrings(2).replace('\n', '')))))
def inputST(): ''' Accept input of beginning time of the period. :return string: strings of beginning of the period for API's URL. ''' lang = language.Language('een_date/set_date') return (sTd2STs(datecheck(raw_input(lang.getStrings(1).replace('\n', '')))))
def fileout(self, file_name): lang = language.Language('een_video/get_video') if self.response.status_code == 200: with open(file_name, 'wb') as file: self.response.raw.decode_content = True shutil.copyfileobj(self.response.raw, file) print(lang.getStrings(4).replace('\n', '')) else: print(lang.getStrings(5).replace('\n', '')) print(self.response.status_code),
def createdir(dirname): ''' Simply create a directory. :param string dirname: the directory's name. ''' lang = language.Language('een_account/operate_account') try: if not os.path.exists(dirname): os.mkdir(dirname) except: print(lang.getStrings(0).replace('\n','')) dirname = '.' return(dirname)
def filedl(self, iurl, file_name): lang = language.Language('een_video/get_video') try: print(lang.getStrings(6).replace('\n', '') + iurl.encode('utf-8')) self.response = requests.get(iurl, cookies=self.cookie, stream=True) self.fileout(file_name) except AttributeError: print(lang.getStrings(8).replace('\n', '')) except: print(lang.getStrings(9).replace('\n', ''))
def accountlist(cookie): ''' Display subaccount list method. :param string cookie: Current session's cookie. ''' lang = language.Language('een_account/get_account') accounts = get_accountlist(cookie) if accounts.status_code == 200: def printer(string): print(string) [printer(i[1] + ' (ID: ' + i[0] + ' )') for i in accounts.json()] elif accounts.status_code == 403: print(lang.getStrings(0).replace('\n', ''))
def make_camlist(): ''' Get a camera list. :return json response: JSON which contains camera list. ''' lang = language.Language('een_device/get_devicelist') response = requests.get('https://login.eagleeyenetworks.com/g/device/list?t=camera', cookies=cookie) print(lang.getStrings(0).replace('\n','')) #<camera list> def printer(string): print string [printer(i[1]) for i in response.json()] return response
def reset_account(cookie): ''' Reset current master account. :param strings cookie: Current session's cookie. ''' lang = language.Language('een_account/set_account') response = requests.post( 'https://login.eagleeyenetworks.com/g/aaa/switch_account', cookies=cookie) print(response) if response.status_code == 200: print(lang.getStrings(0).replace('\n', '')) #Success returning to master account. else: print(lang.getStrings(1).replace('\n', ''))
def devicelistcsvo(gcookie): #This method will be joint into a common method. ''' Get and make a device list and convert to CSV format. And this method check to sub account's devices if current account has sub account. Send device list to the CSV maker. :param string gcookie: Current session's cookie. ''' global cookie cookie = gcookie lang = language.Language('een_device/get_devicelist') keylist = [u'camera_property_model',u'bridge',u'camera_state_version',u'intf', u'tagmap_status_state',u'camera_property_make',u'camera_retention_asset',u'camera_newest',u'camera_oldest',u'connect', u'uuid',u'service',u'camera_retention_etag',u'make',u'ipaddr',u'ts',u'r_model',u'version',u'admin_password',u'esn',u'status', u'admin_user',u'r_make',u'camera_property_version',u'r_version',u'mac',u'register_id',u'bridgeid',u'now',u'camera_property_analog', u'class',u'status_hex',u'camera_retention_interval',u'camera_now',u'camera_abs_newest',u'camera_abs_oldest',u'camera_valid_ts', u'model',u'camtype',u'proxy'] #Prepare list of lines which will be wrote. strings = [u'account_name,account_id,type,name,' + ','.join(keylist) + ',Number of Attached cameras'] #Check Subaccounts. accounts = ga.subaccountlist(cookie) #Appending current acount's devices to the list. [strings.append(x) for x in [stringer(i, '(Current account),,', keylist) for i in get_devicelist().json()]] #Appending subaccount's devices to the list. def subaccountdig(j): print(lang.getStrings(1).replace('\n','') + j.encode('utf-8')) #Changing to subaccount: sa.set_account(j, cookie) [strings.append(x) for x in [stringer(i, accounts[1][accounts[0].index(j)] + u',' + j + u',', keylist) for i in get_devicelist().json()]] sa.reset_account(cookie) if accounts != None: [subaccountdig(j) for j in accounts[0]] strings = number_of_cameras(strings) #Export to a file. filer = export.Filer() filer.fileout(strings, 'devicelist')
def dl_bridgeinfo(cookie): ''' Get bridge information and write it to a file. :param string cookie: Current session's cookie. ''' global gcookie gcookie = cookie lang = language.Language('een_device/get_bridge') bridge = raw_input(lang.getStrings(3).replace('\n', '')) #Bridge ID >>> bridgeinfo = get_bridge(bridge) print(bridgeinfo) if bridgeinfo.status_code == 200: #Completely got bridge information. filer = export.Filer() filer.fileout(bridgeinfo, 'bridge_' + bridge) else: print(lang.getStrings(4).replace('\n', ''))
def datecheck(date_str): ''' Given strings of specified date to check and format to datetime format. :param string date_str: Strings of specified date. :return datetime date_formatted: formated date. :return None None: Format failure. ''' lang = language.Language('een_date/set_date') try: #Try to format. date_formatted = datetime.datetime.strptime(date_str, "%Y/%m/%d %H:%M:%S") print(date_formatted) return (date_formatted) except ValueError: print(lang.getStrings(0).replace('\n', '')) #Date format error! return None
def video_download(camid, STd, ETd, cookie): ''' Download all videos in the specified camera in the specified period, With multi threading. :param string camid: Specified camera's ID :param string STs: Start date time of specified period. :param string ETs: End date time of specified period. :param string cookie: Current session's cookie. ''' lang = language.Language('een_video/get_video') try: videotimelist = get_videotimelist(camid, STd, ETd, cookie) except: print(lang.getStrings(3).replace('\n', '')) raise TypeError dirname = 'camera_' + camid dirname = od.createdir(dirname) if videotimelist == None: print(lang.getStrings(8).replace('\n', '')) return 0 #Number of threads. thread_num = 4 url = make_url(videotimelist, camid) dlinfo = [dirname, camid, videotimelist, url, cookie] spurl = divideurl(url, thread_num) #Multi threading threads = [] [ threads.append( MyThread("Thread-{}".format(spurl.index(iurl)), iurl, dlinfo)) for iurl in spurl ] for th in threads: th.start() sleep(1) [th.join() for th in threads] print(camid.encode('utf-8') + lang.getStrings(7).replace('\n', ''))
def subaccountlist(cookie): ''' Make a current user's sub account list and return the sub account list. :param string cookie: Current session's cookie. :param list accounts: Subaccount's list --->[account name, account id] ''' lang = language.Language('een_account/get_account') print(lang.getStrings(1).replace('\n', '')) #Checking subaccounts. response = get_accountlist(cookie) if response.status_code == 200: print(lang.getStrings(2).replace('\n', '')) #Subaccounts found. accounts = [[], []] [accounts[0].append(i[0]) for i in response.json()] [accounts[1].append(i[1]) for i in response.json()] else: print(lang.getStrings(3).replace('\n', '')) #No subaccounts was found. accounts = None return accounts
def get_videotimelist(camid, STs, ETs, cookie): ''' Get and make a list of time that the specified camera's video in the specified period exists. :param string camid: The specified camera's ID. :param string STs: Start date time of the period. :param string ETs: End date time of the period. :param string cookie: Current session's cookie. :return JSON response: A response of EEN API include the video's start time and end time lists. ''' lang = language.Language('een_video/get_video') query = 'https://login.eagleeyenetworks.com/asset/list/video?start_timestamp=' + STs + '.000;end_timestamp=' + ETs + '.000;id=' + camid + ';options=coalesce' response = requests.get(query, cookies=cookie) print(response) if response.status_code == 200 and not response.json() == []: return (response) elif response.status_code == 400: print(camid.encode('utf-8') + lang.getStrings(0).replace('\n', '')) print( lang.getStrings(1).replace('\n', '') + str(response.status_code).encode('utf-8')) elif response.json() == []: print(camid.encode('utf-8') + lang.getStrings(2).replace('\n', ''))
def downloadvideos(cookie) : ''' Download videos with get_video module. :param string cookie: Current session's cookie. ''' lang = language.Language('een_video/dl_videos') camera = raw_input(lang.getStrings(0).replace('\n','')) #Enter camera id or ALL >>> if camera == 'ALL': #Download current user's all camera's videos. camlist = gd.cameras(cookie) else: #Download specified camera's videos. camlist = [camera] try: #Trying to download videos. STs = sdt.inputST() ETs = sdt.inputET() if STs == None or ETs == None: #The specified period has wrong. raise TypeError print(lang.getStrings(1).replace('\n','')) #Go download. [gv.video_download(i, STs, ETs, cookie) for i in camlist] except: print(lang.getStrings(2).replace('\n',''))
def menu_bridgeinfo(cookie): ''' Display this package's menu. :param string cookie: Current session's cookie. ''' lang = language.Language('een_device/menu_device') while True: print(lang.getStrings(0).replace('\n', '')) #1 to display your bridge list (include version information) print(lang.getStrings(1).replace('\n', '')) #2 to download detailed information of the specified bridge print(lang.getStrings(2).replace('\n', '')) #3 to download informations of your devices as a raw JSON file print(lang.getStrings(3).replace('\n', '')) #4 to download and export your device list as a CSV file print(lang.getStrings(4).replace('\n', '')) #5 to display your bridge metrics print(lang.getStrings(5).replace('\n', '')) #6 to download and export your bridge metrics as a CSV file print(lang.getStrings(6).replace('\n', '')) #0 to return to menu mode = raw_input('>>> ') if mode == '1': #Show bridge list gb.show_bridges(cookie) elif mode == '2': #Download bridge's information gb.dl_bridgeinfo(cookie) elif mode == '3': #Output Raw JSON of a camera's informtaion. gd.devicelisto(cookie) elif mode == '4': #Export CSV of current user's device list. gd.devicelistcsvo(cookie) elif mode == '5': #Download bridge's information gm.show_metrics(cookie) elif mode == '6': #Download bridge's information gm.dl_bridgemetric(cookie) elif mode == '0': break
def dl_bridgemetric(cookie): #This method will be joint into a common method. ''' Download bridge's metrics and export to a CSV file. :param string cookie: Current session's cookie. ''' lang = language.Language('een_device/get_metric') global gcookie gcookie = cookie def printer(string): #printer print(string) def metrics(bridge): try: m = get_bridgemetric(bridge).json() bri_info = gb.get_device(bridge, gcookie).json()['camera_info'] a = m['core'] b = m['bandwidth'] sumb = 0 length = 0 aveb = 0 for bi in b: sumb += bi[1] length += 1 if length != 0: aveb = sumb / length try: r = (sd.string2DateTime(a[-1][0]).strftime('%Y/%m/%d %H:%M:%S') + ',' + str(a[-1][1] / (1024**2)) + ',' + str(a[-1][2] / (1024**2)) + ',' + str((a[-1][1] - a[-1][2]) / (1024**2)) + ',' + str(a[-1][5] / (1024**2)) + ',' + str(a[-1][4] / (1024**2)) + ',' + str(aveb * 8 / (1024**2)) + ',' + bri_info[u'version'] + ',') except: r = (sd.string2DateTime(a[-1][0]).strftime('%Y/%m/%d %H:%M:%S') + ',' + str(a[-1][1] / (1024**2)) + ',' + str(a[-1][2] / (1024**2)) + ',' + str((a[-1][1] - a[-1][2]) / (1024**2)) + ',' + str(a[-1][5] / (1024**2)) + ',' + str(a[-1][4] / (1024**2)) + ',' + str(aveb * 8 / (1024**2)) + ',' + '' + ',') return(r) except ValueError: return(u'N/A,,,') accounts = ga.subaccountlist(gcookie) strings = [u'subaccount name,subaccount id,bridgename,bridgeID,' + 'last check date,total disk space(GiB),average free disk space(GiB),' + 'average used disk space(GiB),MebiBytes streamed,MebiBytes shaped,Cloud BM Measured(Mbps),Firmware Version\r\n'] #Current account's bridges. [strings.append('(Current account),,' + i[2] + u',' + i[1] + u',' + metrics(i[1]) + u'\r\n') for i in gb.make_bridgelist(gcookie).json() if metrics(i[1]) != None] #[8][8] #401deru #Subaccounts bridges. def loop(j): print(lang.getStrings(3).replace('\n','') + j.encode('utf-8')) #Changing to subaccount: sa.set_account(j,cookie) [strings.append(accounts[1][accounts[0].index(j)] + u',' + j + u',' + i[2] + u',' + i[1] + u',' + metrics(i[1]) + u'\r\n') for i in gb.make_bridgelist(gcookie).json() if metrics(i[1]) != None] #[8][8] sa.reset_account(cookie) if accounts != None: [loop(j) for j in accounts[0]] filer = export.Filer() filer.fileout(strings, 'bridgemetrics')