From 20b6d5439e28bc6c75cb07ae0d0c3d4bf30b5694 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Joonas=20Sepp=C3=A4?= <joasep@utu.fi>
Date: Sat, 26 Mar 2022 21:00:57 +0200
Subject: [PATCH] Better news program

---
 .vscode/launch.json                    |  14 +++
 __pycache__/myNewsClass.cpython-39.pyc | Bin 2122 -> 3897 bytes
 myNews.py                              |   9 +-
 myNewsClass.py                         | 140 ++++++++++++++++++++++---
 4 files changed, 148 insertions(+), 15 deletions(-)
 create mode 100644 .vscode/launch.json

diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 0000000..2a71b20
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,14 @@
+{
+    // Use IntelliSense to learn about possible attributes.
+    // Hover to view descriptions of existing attributes.
+    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+    "version": "0.2.0",
+    "configurations": [
+        {
+            "type": "pwa-chrome",
+            "request": "launch",
+            "name": "Open jsProject.html",
+            "file": "/Users/joonasseppa/Desktop/Koulu/training/jsProject.html"
+        }
+    ]
+}
\ No newline at end of file
diff --git a/__pycache__/myNewsClass.cpython-39.pyc b/__pycache__/myNewsClass.cpython-39.pyc
index f6814a0a7a12bd8e8fdc518f1272d3e82e065d54..6f255d5eee68e1ec444027d4c47f68c8a4f9b7e1 100644
GIT binary patch
literal 3897
zcmYe~<>g{vU|@Lt{9huQGy}t95C<7EGcYhXFfcF_ConKDq%fo~<}gG-XvQc;FrO)k
zDTN`0DTg_iC5nX+B*&b?n#&f&mdhT+4(2oFaO83_F)%XZaz$}NMR=lk+!<0>QdnCU
zQdparqIgpngBdj0UV`lQ(`3BGURsosUyz!o$#jdgAhD=8^%ggn3N9(i%u7!ODMQ9g
zFlUM|FfgPtfSeY^l){+8)WQ(OoWdN;pviKJ*Dtla*s0PvzcjC;s4^L(1!jZ*0|Nsq
z0|SFI$fs5;3=B04DU8`nMXO2}7BHqTEo7`^Dq&i{T*H*bvXHTs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go#oOi%K$+b5f&(
z3QCi5GK(`3lX6lWAz~{Tio_Tg7=F1sTg8MHrxq2*c;)BkB^JlHq!wqF<QK$v=a=S`
z%EXiuC1&Pj=B39JRF-7q=lP|U7Y7vOrxzvW#!Ob=m52pp!Qv25eq`ccWMkxDL?t;G
zxtQ1(1(<o5xEOhuc%UjEG#3j86B`o`qXd%~lNloy6Au#)69*#?BL|!{S(eYCUV?!E
z;#RPOA%r+cjG2Lf0p!(UP-t;56@mDgY*Au~#g%!<nfZF<nRzMs<;C%-WvO{3#o#b4
u;s<FI1Q8-20;C0EA}BB*ERfl^IBatBQ%ZAE?HC0>WedocJYdgpFaZGbb|Rbr

diff --git a/myNews.py b/myNews.py
index 2cb67e6..a7c3240 100644
--- a/myNews.py
+++ b/myNews.py
@@ -1,7 +1,14 @@
 from myNewsClass import NewsByCountry
 
 print()
+number=5
 while(True):
     print("If you need instructions, type 'info'")
     print("What country do you want news from?: ")
-    NewsByCountry.callNews(input())
\ No newline at end of file
+    userInput = input()
+    if userInput=="exit":
+        break
+    number = NewsByCountry.callNews(userInput, number)
+    #If number -1 is returned, an error has happened
+    if number == -1:
+        break
\ No newline at end of file
diff --git a/myNewsClass.py b/myNewsClass.py
index 68346ba..07f1f33 100644
--- a/myNewsClass.py
+++ b/myNewsClass.py
@@ -1,13 +1,60 @@
-from asyncio.windows_events import NULL
 import requests
 import json
 import textwrap
+from urllib.request import urlopen
+#import xml.parsers.expat
+from xml.dom.minidom import parse, parseString
+import xml.etree.ElementTree as ET
+import xmltodict
 
 class NewsByCountry:
     
-    def callNews(countryString):
+    def callNews(countryString, number):
+        if(countryString=="iltalehti"):
+            iltalehtiURL = requests.get("https://www.iltalehti.fi/rss/uutiset.xml")
+            
+            iltalehtiDICT = xmltodict.parse(iltalehtiURL.content)
+
+            #MUUTIN TÄSSÄ DICT-FORMAATIN JSON:iksi. Nähtävästi DICT toimii jo samalla tavalla.
+            #PIDETÄÄN KUITENKIN KOODI TÄSSÄ JOS JSON:ia TARVITSEE!
+            #iltalehtiJSON = json.dumps(iltalehtiDICT)
+            #iltalehtiJSONOikea = json.loads(iltalehtiJSON)
+
+            #json.loads MUUTTAA JSON:IN DICTIONARYKSI; siis iltalehtiJSONOikea~iltalehtiDICT
+            #Tyyppi ei ole täysin sama; toinen on ordered dictionary ja toinen perus dictionary
+            #Mutta joka tapauksessa, pythonissa kannattaa käyttää dictionarya koska JSON:sta ei  voi ottaa
+            #osia helposti
+
+            #iltalehti = iltalehtiJSONOikea["rss"]["channel"]["item"]
+
+            iltalehti = iltalehtiDICT["rss"]["channel"]["item"]
+
+            for i in range(10):
+                print()
+            
+
+            howManyToShow = 0
+
+            if number > len(iltalehti):
+                howManyToShow = len(iltalehti)
+            elif number <= len(iltalehti):
+                howManyToShow = number
+
+
+            for i in range(howManyToShow):
+                #print(iltalehti[i]["title"])
+                
+                publishableArticle = textwrap.wrap(iltalehti[i]["description"], 80)
+
+                for i in publishableArticle:
+                    print(i)
+                print()
+
+            return number
 
         if(countryString=="info"):
+            for i in range(10):
+                print()
             print()
             print("Hello! Welcome to my news-program!")
             print("This program uses 'newsapi.org' to get news from different sources")
@@ -15,13 +62,36 @@ class NewsByCountry:
             print("To get news from a country, input country's short form, eg. 'us'")
             print("Country names must be written in lower-case")
             print()
+            print("To change the amount of news, input an integer, eg. '10'")
+            print()
+            print("If you wan't to leave the program, input 'exit'")
+            print()
+            print("In Finnish you can get news from Iltalehti with input 'iltalehti'")
+            print()
             print("All possible country inputs are: ")
             print("at, au, be, bg, br, ca, ch, cn, co, cu, cz, de, eg, fr, gb, gr, hk, hu, id, ie, il, in, it, jp, kr, lt, lv, ma, mx, my, ng, nl, no, nz, ph, pl, pt, ro, rs, ru, sa, se, sg, si, sk, th, tr, tw, ua, us, ve, za")
             print("Please note that news can can be in other languages than English!")
             print()
+            #Update this list when you can
+            print("You can find news in English from: au = Australia, ca = Canada, gb = Great Britain, us = USA")
+            print("And possibly from: hk=Hong Kong, ie = Ireland, in=India, jp=Japan, mx=Mexico, nz=New zealand, sg=singapore, za=south africa")
+            print()
         else:
+            if countryString.isnumeric():
+                newNumber = int(countryString)
+                number = newNumber
+                for i in range(10):
+                    print()
+                print("Number of news changed to " + str(number))
+                print() 
+                return number
+            
+            for i in range(10):
+                print()
+
             print()
-            print("Top 5 news from '" + countryString + "':")
+            print("Top " + str(number) + " news from '" + countryString + "':")
+
 
 
             url = "https://newsapi.org/v2/top-headlines?country=" + countryString + "&apiKey=9a5f1610264d4831b94ba00b1bdbd885"
@@ -29,28 +99,65 @@ class NewsByCountry:
             someCountry = requests.get(url)
             content = json.loads(someCountry.content)
 
-            if(content["totalResults"]<5):
+            if(content["status"]=="ok"):
+                pass
+
+            elif(content["status"]=="error"):
                 print()
-                print("LESS THAN 5 RESULTS")
-                print("This many results: ")
-                print(content["totalResults"])
+                print("Unknown error happened!") 
                 print()
-                print("This probably means that country's name is wrong or country not supported")
+                print("This is what we got from the server: ")
+                print(content)
                 print()
+                number = -1
+                return number
+
             else:
+                if(content["code"]=="rateLimited"):
+                    print()
+                    print("Error!")
+                    print("You have made too many requests")
+                    print("Free accounts are limited to 50 requests in 12 hours")
+                    print()
+                    print("Here is the complete error message from server in JSON format: ")
+                    print(content)
+                    print()
+                    number = -1
+                    return number
 
 
-                articles = content["articles"]
 
+            if(content["totalResults"]<1):
+                print()
+                print("ERROR: 0 RESULTS")
+                #print(str(content["totalResults"]) + " results")
+                #print(content["totalResults"])
+                print()
+                print("This probably means that country's name is wrong or country is not supported")
+                print()
+            else:
+
+
+                articles = content["articles"]
+                results = len(articles)
                 print()
+                printableNumber = 0
+
+                if(number>=len(articles)):
+                    printableNumber = len(articles)
+                else:
+                    printableNumber = number
 
-                for i in range(5):
+
+
+                for i in range(printableNumber):
                     print(((articles[i])["source"])["name"] + ":")
 
-                    if(articles[i]["description"]==NULL or articles[i]["description"]=="" or articles[i]["description"]==" "):
+                    if(articles[i]["description"]==None or articles[i]["description"]=="" or articles[i]["description"]==" "):
                         #Description is null, trying content: 
-                        if(articles[i]["content"]==NULL or articles[i]["content"]=="" or articles[i]["content"]==" "):
-                            print("The content is also null, no can do")
+                        if(articles[i]["content"]==None or articles[i]["content"]=="" or articles[i]["content"]==" "):
+                            print("(This article has no description and no content!)")
+                            print()
                         else:
                             article = articles[i]["content"]
 
@@ -66,4 +173,9 @@ class NewsByCountry:
         
                         for i in publishableArticle:
                             print(i)
-                        print()
\ No newline at end of file
+                        print()
+                if(results<number):
+                    print("Found only " + str(results) + " results!")
+                    print()
+
+        return number
\ No newline at end of file
-- 
GitLab