예제 #1
0
 def send(self, data):
     target = data["target"]
     msg = data["data"]
     pretlist = settings().findtarget(target)
     self.logger(pretlist["status"] == 200, "debug", "yellow")
     if pretlist["status"] == 200:
         self.logger("here")
         try:
             wsdict = self.q.get(False)["websockdict"]
         except Exception as e:
             self.logger(e)
             return
         #self.q.put(wsdict, False) # always put it back
         tlist = pretlist["resource"]
         self.logger(wsdict)
         for t in tlist:
             self.logger(t)
             try:
                 ws = wsdict[t]
                 self.logger("websocket found")
                 self.loop.run_until_complete(ws.send(msg))
                 self.logger("sent")
             except:
                 wsdict.pop(t, "")
         self.q.put({"websockdict": wsdict})  # always put it back
예제 #2
0
    async def msgcheck(self):
        self.logger("pubsub started")
        # pubsub checker to send messages
        while True:
            msg = self.p.get_message()
            if msg and type(msg["data"]) != int:
                msgdata = json.loads(msg["data"].decode())
                category = msgdata["category"]
                target = msgdata["target"]
                if category == "sendmsg":
                    realdata = json.loads(msgdata["data"])
                    category = realdata["category"]
                    msgtype = realdata["type"]
                    data = realdata["data"]
                    metadata = realdata["metadata"]
                    metadata["guid"] = self.createGUID()
                    msg = {
                        "status": 200,
                        "category": category,
                        "type": msgtype,
                        "data": data,
                        "metadata": metadata
                    }

                pretargetlist = settings().findtarget(target)
                if pretargetlist["status"] == 200:
                    targetlist = pretargetlist["resource"]
                    for target in targetlist:
                        await self.MsgHandler.sendbyname(msg, target)
                else:
                    self.logger(pretargetlist["resource"])

            await asyncio.sleep(3)
예제 #3
0
    def getauthentication(self):
        headers = {}
        preapicreds = settings().getsettings("credentials", "hereapi")
        if preapicreds["status"] == 200:
            apicreds = preapicreds["resource"]

            if "access_token" in apicreds:
                expirationdate = apicreds["expires_at"]
                if int(
                        int(time())
                ) < expirationdate:  # token has expired, so ask for a new one
                    accesstoken = apicreds["access_token"]
                else:
                    id = apicreds["key_id"]
                    secret = apicreds["key_secret"]
                    accesstoken = oauth().get_token(id, secret)
            else:  # apparently no token exists yet
                id = apicreds["key_id"]
                secret = apicreds["key_secret"]
                accesstoken = oauth().get_token(id, secret)
        else:  # no settings dict exists, warn user and make them fill it in.
            return {
                "status": 404,
                "resource": "Please link with the HERE location services API."
            }

        headers["Authorization"] = "Bearer " + accesstoken
        return headers
예제 #4
0
    def get_token(self, consumer_key, access_key_secret):
        self.oauth_consumer_key = consumer_key
        self.access_key_secret = access_key_secret

        self.oauth_nonce = str(int(time.time() * 1000))
        self.oauth_timestamp = str(int(time.time()))
        parameter_string = self.create_parameter_string()

        tokendict = self.request_token(parameter_string, self.oauth_url)
        accesstoken = tokendict["access_token"]
        expirationdate = int(time.time()) + int(tokendict["expires_in"])

        creddict = {}
        creddict["access_token"] = accesstoken
        creddict["expires_at"] = expirationdate

        settings().setsettings("credentials", "hereapi", creddict)
        return accesstoken
예제 #5
0
 def __init__(self):
     self.tag = "anime"
     self.r = redis.Redis(host='localhost', port=6379, db=0)
     self.p = self.r.pubsub()
     self.publishchoice = "HorribleSubs"
     self.firstshow = True
     self.watchall = False # change to true to look for all shows
     prelist = settings().getsettings("anime", "list")
     if prelist["status"] == 200:
         self.watchlist = prelist["resource"]
     else:
         # alert user
         self.watchlist = self.findshows()
     predict = settings().getsettings("anime", None)
     if predict["status"] == 200:
         self.maindict = predict["resource"].get("maindict", {})
         #self.maindict = predict["resource"]
         #self.animedict = predict["resource"]
     else:
         self.maindict = {}
예제 #6
0
 def anime(self, eventtype):
     if eventtype == "aired":
         lastshow = settings().getsettings("anime", "lastshow")["resource"]
         premsgdata = settings().getsettings(
             "anime", "maindict")["resource"][lastshow]
         msgdata = {}
         target = "anime"
         msgdata["category"] = "anime"
         msgdata["type"] = "latest"
         datadict = {}
         datadict["title"] = lastshow
         datadict["lastep"] = premsgdata["lastep"]
         datadict["art"] = premsgdata["art"]
         datadict["aired_at"] = premsgdata["aired_at"]
         msgdata["data"] = datadict
         msgdata["metadata"] = {"target": "anime", "status": 200}
         #finalmsg = json.dumps({"command":"sendmsg", "msg":msgdata, "target":target})
         finalmsg = {"command": "sendmsg", "msg": msgdata, "target": target}
         self.send(finalmsg)
     if eventtype == "compressed":
         pass
예제 #7
0
    def getnextdeparturesatstop(self, busstopid=None):
        if not busstopid:
            prebusstop = settings().getsettings("Personalia", "homebusid")
            if prebusstop["status"] == 200:
                busstopid = prebusstop["resource"]
            else:
                # alert the user to ask for busstop id
                pass
        url = "https://transit.hereapi.com/v8/departures"
        headers = self.getauthentication()
        params = {"ids": busstopid}

        result = requests.get(url=url, params=params, headers=headers)
        return result.json()
예제 #8
0
    def loopfunc(self):
        self.logger("in loop func!", "info", "blue")
        while True:
            lst = settings().getsettings("anime", "maindict")["resource"]

            chosenshow = list(lst.keys())[random.randint(0, len(lst) - 1)]
            preshowdict = lst[chosenshow]

            title = chosenshow
            imagelink = preshowdict["art"]["cover"]
            bannerlink = preshowdict["art"]["banner"]
            episode = preshowdict["lastep"]
            timestamp = preshowdict["aired_at"]

            showdict = {
                "title": title,
                "lastep": episode,
                "aired_at": timestamp,
                "art": {
                    "cover": imagelink,
                    "banner": bannerlink
                }
            }
            category = "tests"
            type = "replace"
            metadata = {"target": "anime", "guid": self.createGUID()}
            finaldict = {
                "status": 200,
                "command": category,
                "type": type,
                "data": showdict,
                "metadata": metadata
            }

            for ws in self.socketlist:
                self.sendmsg(ws, finaldict)

            # weather
            #results = weather().getcurrentweather()["resource"]
            #self.logger(results)

            #metadata = {"target":"weather", "guid": self.createGUID()}

            #finaldict = {"status": 200, "category": "weather", "type": "current", "data": results, "metadata":metadata}
            #for ws in self.socketlist:
            #self.sendmsg(ws, finaldict)

            sleep(15)
예제 #9
0
    def getshows(self, number = 1):
        base = f"https://nyaa.si/?page=rss&q={self.publishchoice}+%2B+[1080p]&c=1_2&f=2"
        feed = feedparser.parse(base)
        entries = feed.entries
        sessiondict = {}
        x = 0
        while x < number:
            try:
                entry = entries[x]
            except IndexError:
                self.logger(f"Tried index {x} and failed.")
                break
            except Exception as e:
                self.logger("I tried logging.", "alert", "blue")
            title, show, episode = self.cleantitle(entry["title"])
            link = entry["link"]
            if self.watchall:
                self.watchlist.append(show)
            if show in self.watchlist:
                sessiondict["command"] = "anime"
                sessiondict["title"] = show
                sessiondict["episode"] = episode
                if show not in self.maindict:
                    imagelink, bannerlink, maxepisodes = self.getinfo(show) #TODO add synopsis
                    self.maindict[show] = {"art":{}, "meta":{}}
                    self.maindict[show]["art"]["cover"] = imagelink
                    self.maindict[show]["art"]["banner"] = bannerlink
                    self.maindict[show]["meta"]["maxepisodes"] = maxepisodes
                sessiondict["art"] = {}
                sessiondict["art"]["cover"] = self.maindict[show]["art"]["cover"]
                sessiondict["art"]["banner"] = self.maindict[show]["art"]["banner"]

                self.maindict[show]["lastep"] = episode
                animedict = settings().getsettings("anime", None)["resource"]
                self.logger(animedict["lastshow"])
                if animedict.get("lastshow", "show") != show:
                    self.download(show, link)
                    ct = int(time.time())
                    self.maindict[show]["aired_at"] = ct
                    sessiondict["aired_at"] = ct
                    targetlist = settings().checkavailability("computing")["resource"]
                    if len(targetlist) == 0:
                        Event().anime("aired")
                if self.firstshow:
                    self.firstshow = False
                    settings().setsettings("anime", "lastshow", show)
                    self.r.set("lastshow", json.dumps(sessiondict))
                x += 1
            else:
                number += 1
                x += 1
        self.r.set("animedict", json.dumps(self.maindict))
        settings().setsettings("anime", "maindict", self.maindict)
        
        return sessiondict
예제 #10
0
    def findshows(self):
        from bs4 import BeautifulSoup

        url = "https://horriblesubs.info/current-season/"
        html = requests.get(url)
        soup = BeautifulSoup(html.text, "html.parser")
        preshows = soup.find_all(class_="ind-show")
        showlist = []
        chosenlist = []
        for show in preshows:
            showlist.append(show.find("a")["title"])

        for i, show in enumerate(showlist):
            print("Show number {} is: {}".format(i + 1, show))
            interest = input("w to add {}".format(show))
            if interest == "w":
                chosenlist.append(show)
        result = settings().setsettings("anime", "list", chosenlist)
        
        return result
    async def messagehandler(self, ws, message):
        self.logger(message, "debug", "blue")
        category = message["category"]
        type = message["type"]
        data = message.get("data", {})  # optional
        metadata = message["metadata"]
        id = metadata.get("id", None)
        if id:
            self.logger("updating activity..", "debug", "yellow")
            settings().updateactivity(id, True)
        address = ws.remote_address[0]
        self.logger(metadata, "info", "blue")
        self.logger(message, "debug", "yellow")
        if "guid" not in metadata:  # for tracking purposes
            metadata["guid"] = self.createGUID()
            self.logger("added guid!")

        if category == "help":
            if type == "anime":
                methods = ["list", "latest", "showinfo"]
                helpdata = data.get("method") or None
                if helpdata == None:
                    message = "Please try inserting one of the methods as data, like: data:{\"method\":\"list\"}"
                    finaldict = {
                        "status": 200,
                        "methods": methods,
                        "message": message,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, message,
                                                    metadata)
                    await self.sendmsg(ws, finaldict)
                elif helpdata == "list":
                    message = "TODO implement help message"
                    finaldict = {
                        "status": 200,
                        "message": message,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, message,
                                                    metadata)
                    await self.sendmsg(ws, finaldict)
                elif helpdata == "latest":
                    message = "TODO implement help message"
                    finaldict = {
                        "status": 200,
                        "message": message,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, message,
                                                    metadata)
                    await self.sendmsg(ws, finaldict)
                elif helpdata == "showinfo":
                    message = "TODO implement help message"
                    finaldict = {
                        "status": 200,
                        "message": message,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, message,
                                                    metadata)
                    await self.sendmsg(json.dumps(finaldict))

        if category == "admin":
            if type == "signin":
                name = data["name"]
                devtype = data["devtype"]
                subs = data["subscriptions"]
                capabilities = data["capabilities"]
                newdata = {
                    "name": name,
                    "devtype": devtype,
                    "subscriptions": subs,
                    "lastaddress": address,
                    "capabilities": capabilities
                }
                result = settings().setusersettings(newdata)
                self.logger(result, "debug", "yellow")
                if result["status"] == 201:  # 201 because creation
                    self.logger(result["resource"], "debug")
                    id = result["resource"]["id"]
                    settings().updateactivity(id, True)
                    category = "admin"
                    type = "signinresponse"
                    data = {"id": id}
                    metadata = {"status": 200}
                    msg = self.messagebuilder(category, type, data, metadata)
                    self.savesocket(ws, id)
                else:  # maybe do different error codes here at some point
                    category = "admin"
                    type = "signinresponse"
                    data = {"resource": "failed to sign in"}
                    metadata = {"status": 503}
                    msg = self.messagebuilder(category, type, data, metadata)
                await self.sendmsg(ws, msg)
                self.logger("Sent Message!", "debug", "red")

        if category == "test":
            if type == "failure":
                data = {"message": "Failure is not acceptable"}
                finaldict = self.messagebuilder(category, type, data)
                await self.sendmsg(ws, finaldict)

            if type == "long":
                data = {"message": "Pfft that took a while.."}
                finaldict = self.messagebuilder(category, type, data)

                sleep(5)
                await self.sendmsg(ws, finaldict)

            if type == "short":
                data = {"message": "That was quick!"}
                finaldict = self.messagebuilder(category, type, data)
                await self.sendmsg(ws, finaldict)

        if category == "anime":
            if type == "list":
                prenamelist = settings().getsettings("anime", "list")
                preanimedict = settings().getsettings("anime", "maindict")
                if prenamelist["status"] == 200:
                    anilist = []
                    namelist = prenamelist["resource"]
                    maindict = preanimedict["resource"]
                    for name in namelist:
                        if name in maindict:
                            entry = maindict[name]
                            entry["title"] = name
                            anilist.append(entry)
                    data = {"list": anilist}
                    finaldict = {
                        "status": 200,
                        "category": category,
                        "type": type,
                        "data": data,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, data,
                                                    metadata)
                    await self.sendmsg(ws, finaldict)

                else:
                    data = {"error": "error"}
                    finaldict = {
                        "status": 500,
                        "category": category,
                        "type": type,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, data,
                                                    metadata)
                    await self.sendmsg(ws, finaldict)

            if type == "latest":
                preanidict = settings().getsettings(
                    "anime")  # get full anime dict
                if preanidict["status"] == 200:
                    anidict = preanidict["resource"]
                    latestshow = anidict["lastshow"]  # catch errors for these
                    anilist = anidict["list"]
                    maindict = anidict["maindict"]
                    showinfo = maindict[latestshow]
                    showinfo["title"] = latestshow
                    finaldict = {
                        "status": 200,
                        "category": category,
                        "type": type,
                        "data": showinfo,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, showinfo,
                                                    metadata)
                    await self.sendmsg(ws, finaldict)

            if type == "showinfo":
                targetshow = data["show"]
                premaindict = settings().getsettings("anime", "maindict")
                if premaindict["status"] == 200:
                    maindict = premaindict["resource"]
                    showinfo = maindict[targetshow]  # might not exist
                    showinfo["title"] = targetshow
                    finaldict = {
                        "status": 200,
                        "category": category,
                        "type": type,
                        "data": showinfo,
                        "metadata": metadata
                    }
                    finaldict = self.messagebuilder(category, type, showinfo,
                                                    metadata)
                    await self.sendmsg(ws, finaldict)

        if category == "weather":  # requires a known and recent location.
            if type == "current":
                # TODO remove when implemented
                data = weather().getcurrentweather()["resource"]
                self.logger(data)
                finaldict = self.messagebuilder(category, type, data, metadata)
                await self.sendmsg(ws, finaldict)
        if category == "calendar":
            # TODO remove when implemented
            finaldict = {
                "status": 501,
                "category": category,
                "metadata": metadata
            }
            await self.sendmsg(ws, finaldict)

        if category == "monitor":
            # TODO remove when implemented
            finaldict = {
                "status": 501,
                "category": category,
                "metadata": metadata
            }
            await self.sendmsg(ws, finaldict)
예제 #12
0
    def messagehandler(self, ws, message):
        message = json.loads(message)

        category = message["category"]
        type = message["type"]
        data = message.get("data", {})  # optional
        metadata = message.get("metadata", {})  # optional

        self.logger(metadata, "info", "blue")
        if "guid" not in metadata:  # for tracking purposes
            metadata["guid"] = self.createGUID()
            self.logger("added guid!")

        if category == "admin":
            if type == "signin":
                #TODO implement sign in process
                pass
        if category == "test":
            if type == "failure":
                finaldict = {
                    "status": 406,
                    "category": category,
                    "type": type,
                    "data": {
                        "message": "Failure is not acceptable"
                    }
                }
                self.sendmsg(ws, finaldict)

            if type == "long":
                finaldict = {
                    "status": 200,
                    "category": category,
                    "type": type,
                    "data": {
                        "message": "Pfft that took a while.."
                    }
                }
                sleep(5)
                self.sendmsg(ws, finaldict)

            if type == "short":
                finaldict = {
                    "status": 200,
                    "category": category,
                    "type": type,
                    "data": {
                        "message": "That was quick!"
                    }
                }
                self.sendmsg(ws, finaldict)

        if category == "anime":
            if type == "help":
                methods = ["list", "latest", "showinfo"]
                helpdata = data["method"] or None
                if helpdata == None:
                    message = "Please try inserting one of the methods as data, like: data:{\"method\":\"list\"}"
                    finaldict = {
                        "status": 200,
                        "methods": methods,
                        "message": message,
                        "metadata": metadata
                    }
                    self.sendmsg(ws, finaldict)
                elif helpdata == "list":
                    message = "TODO implement help message"
                    finaldict = {
                        "status": 200,
                        "message": message,
                        "metadata": metadata
                    }
                    self.sendmsg(ws, finaldict)
                elif helpdata == "latest":
                    message = "TODO implement help message"
                    finaldict = {
                        "status": 200,
                        "message": message,
                        "metadata": metadata
                    }
                    self.sendmsg(ws, finaldict)
                elif helpdata == "showinfo":
                    message = "TODO implement help message"
                    finaldict = {
                        "status": 200,
                        "message": message,
                        "metadata": metadata
                    }
                    self.sendmsg(json.dumps(finaldict))

            if type == "list":
                prenamelist = settings().getsettings("anime", "list")
                preanimedict = settings().getsettings("anime", "maindict")
                if prenamelist["status"] == 200:
                    anilist = []
                    namelist = prenamelist["resource"]
                    maindict = preanimedict["resource"]
                    for name in namelist:
                        if name in maindict:
                            entry = maindict[name]
                            entry["title"] = name
                            anilist.append(entry)
                    finaldict = {
                        "status": 200,
                        "category": category,
                        "type": type,
                        "data": {
                            "list": anilist
                        },
                        "metadata": metadata
                    }
                    self.sendmsg(ws, finaldict)

                    #TODO remove this testing message
                    finaldict = {
                        "status": 406,
                        "message": "Failure is not acceptable"
                    }
                    self.sendmsg(ws, finaldict)

                else:
                    finaldict = {
                        "status": 500,
                        "category": category,
                        "type": type,
                        "metadata": metadata
                    }
                    self.sendmsg(ws, finaldict)

            if type == "latest":
                preanidict = settings().getsettings(
                    "anime")  # get full anime dict
                if preanidict["status"] == 200:

                    anidict = preanidict["resource"]
                    latestshow = anidict["lastshow"]  # catch errors for these
                    anilist = anidict["list"]
                    maindict = anidict["maindict"]
                    showinfo = maindict[latestshow]
                    showinfo["title"] = latestshow
                    finaldict = {
                        "status": 200,
                        "category": category,
                        "type": type,
                        "data": showinfo,
                        "metadata": metadata
                    }
                    self.sendmsg(ws, finaldict)

            if type == "showinfo":
                targetshow = data["show"]
                premaindict = settings().getsettings("anime", "maindict")
                if premaindict["status"] == 200:
                    maindict = premaindict["resource"]
                    showinfo = maindict[targetshow]  # might not exist
                    showinfo["title"] = targetshow
                    finaldict = {
                        "status": 200,
                        "category": category,
                        "type": type,
                        "data": showinfo,
                        "metadata": metadata
                    }
                    self.sendmsg(ws, finaldict)

        if category == "weather":
            # TODO remove when implemented
            results = weather().getcurrentweather()["resource"]
            self.logger(results)
            finaldict = {
                "status": 200,
                "category": category,
                "type": "current",
                "data": results,
                "metadata": metadata
            }

            self.sendmsg(ws, finaldict)

            if type == "current":  # require data to include location
                # TODO implement
                pass

        if category == "calendar":
            # TODO remove when implemented
            finaldict = {
                "status": 501,
                "category": category,
                "metadata": metadata
            }
            self.sendmsg(ws, finaldict)

        if category == "monitor":
            # TODO remove when implemented
            finaldict = {
                "status": 501,
                "category": category,
                "metadata": metadata
            }
            self.sendmsg(ws, finaldict)
예제 #13
0
    def getcurrentweather(self):
        self.logger("CHANGE WEATHER INTERVAL", "alert", "red")
        prelocation = settings().getsettings("personalia",
                                             "location")["resource"]

        if "coords" not in prelocation:
            self.logger("Unable to find coordinates", "alert", "red")
            # ask for location(TODO: modules > getlocation?)
            # then try again
            #self.getforecast()

        lat, lon = prelocation["coords"]
        if "apikey" not in prelocation:
            self.logger("Weather api key not found.", "alert", "red")
            # run setup(TODO) again, explicitely asking for the weather api key.
            # then try again
            #self.getforecast()

        title = prelocation[
            "city"]  # if coords are in, city name will also be in
        apikey = prelocation["apikey"]

        baseurl = f"https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&appid={apikey}&units=metric"

        #TODO try-catch this HTTP request
        res = requests.get(baseurl).json()
        if len(res.keys()) == 2:
            # error occured, read message
            self.logger(f"Error: {res['cod']}", "alert", "red")
            self.logger(f"Message: {res['message']}", "alert", "red")

        try:
            timezone = res["timezone"]
            # maybe write to file

            # current weather
            curdict = {}
            cur = res["current"]
            dt = int(time.time())  # time of request, unix, utc
            temp = cur["temp"]
            sunrise = cur["sunrise"]
            sunset = cur["sunset"]
            clouds = cur["clouds"]  # cloudiness in %
            rain = cur.get("rain", None)
            windspeed = cur["wind_speed"]
            icon = cur["weather"][0]["icon"]
            iconbase = "http://openweathermap.org/img/wn/"
            iconurl = iconbase + icon + "@2x.png"
            curdict = {
                "location": title,
                "time": dt,
                "temp": temp,
                "rain": rain,
                "sunrise": sunrise,
                "sunset": sunset,
                "clouds": clouds,
                "windspeed": windspeed,
                "iconurl": iconurl
            }
            # cache this to file, maybe?
            preoldweather = settings().getsettings("weather", "current")
            if preoldweather["status"] == 200:
                oldweather = preoldweather["resource"]
                oldtime = oldweather["time"]
                timediff = dt - oldtime
                if timediff > self.refreshtime:
                    settings().setsettings("weather", "current", curdict)
                    Event().weather(curdict)

            else:
                settings().setsettings("weather", "current", curdict)
                Event().weather(curdict)
            return {"status": 200, "resource": curdict}
        except Exception as e:
            #self.logger(e, "alert", "red")
            traceback.print_exc()
            return {"status": 503, "resource": "something went wrong."}